@runtypelabs/persona 4.7.0 → 4.9.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.
- package/README.md +1 -0
- package/dist/animations/glyph-cycle.cjs +2 -2
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/glyph-cycle.js +2 -2
- package/dist/animations/{types-CSmiKRVa.d.cts → types-4ROVJ1gA.d.cts} +85 -3
- package/dist/animations/{types-CSmiKRVa.d.ts → types-4ROVJ1gA.d.ts} +85 -3
- package/dist/animations/wipe.cjs +2 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-5EIIHQLQ.js +1 -0
- package/dist/chunk-IO5VVUKP.js +3 -0
- package/dist/chunk-IPVK3KOM.js +1 -0
- package/dist/chunk-UPO4GUFC.js +1 -0
- package/dist/codegen.cjs +13 -13
- package/dist/codegen.js +14 -14
- package/dist/context-mentions-7S5KVUTG.js +169 -0
- package/dist/context-mentions-inline-TTCN7ZM2.js +4 -0
- package/dist/context-mentions-inline.cjs +4 -0
- package/dist/context-mentions-inline.d.cts +203 -0
- package/dist/context-mentions-inline.d.ts +203 -0
- package/dist/context-mentions-inline.js +4 -0
- package/dist/context-mentions.cjs +295 -0
- package/dist/context-mentions.d.cts +7025 -0
- package/dist/context-mentions.d.ts +7025 -0
- package/dist/context-mentions.js +295 -0
- package/dist/index.cjs +99 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1507 -182
- package/dist/index.d.ts +1507 -182
- package/dist/index.global.js +88 -56
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +99 -68
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +24 -24
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +17 -0
- package/dist/plugin-kit.d.ts +17 -0
- package/dist/plugin-kit.js +1 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-reconnect-JKIJBHS5.js +1 -0
- package/dist/smart-dom-reader.cjs +18 -17
- package/dist/smart-dom-reader.d.cts +1260 -16
- package/dist/smart-dom-reader.d.ts +1260 -16
- package/dist/smart-dom-reader.js +18 -17
- package/dist/testing.cjs +3 -3
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +260 -58
- package/dist/theme-editor-preview.d.cts +1234 -15
- package/dist/theme-editor-preview.d.ts +1234 -15
- package/dist/theme-editor-preview.js +87 -58
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +1226 -15
- package/dist/theme-editor.d.ts +1226 -15
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +76 -0
- package/dist/theme-reference.d.ts +76 -0
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +2 -2
- package/dist/voice-worklet-player.js +2 -2
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +16 -5
- package/src/artifacts-session.test.ts +178 -0
- package/src/client.test.ts +255 -1
- package/src/client.ts +157 -60
- package/src/components/artifact-card.test.ts +333 -0
- package/src/components/artifact-card.ts +75 -28
- package/src/components/artifact-inline.test.ts +1328 -0
- package/src/components/artifact-inline.ts +920 -0
- package/src/components/artifact-pane.test.ts +1042 -0
- package/src/components/artifact-pane.ts +440 -131
- package/src/components/artifact-preview.test.ts +1155 -0
- package/src/components/artifact-preview.ts +994 -0
- package/src/components/composer-parts.ts +3 -12
- package/src/components/context-mention-button.test.ts +70 -0
- package/src/components/context-mention-button.ts +82 -0
- package/src/components/context-mention-chip.ts +134 -0
- package/src/components/context-mention-menu.test.ts +508 -0
- package/src/components/context-mention-menu.ts +0 -0
- package/src/components/message-bubble.test.ts +175 -0
- package/src/components/message-bubble.ts +177 -19
- package/src/components/panel.ts +7 -10
- package/src/components/pill-composer-builder.test.ts +6 -2
- package/src/components/pill-composer-builder.ts +6 -6
- package/src/components/reasoning-bubble.ts +1 -13
- package/src/components/registry.ts +38 -3
- package/src/components/tool-bubble.ts +1 -13
- package/src/context-mentions-bundle.test.ts +163 -0
- package/src/context-mentions-entry.ts +185 -0
- package/src/context-mentions-inline-entry.test.ts +136 -0
- package/src/context-mentions-inline-entry.ts +226 -0
- package/src/context-mentions-inline-loader.test.ts +30 -0
- package/src/context-mentions-inline-loader.ts +36 -0
- package/src/context-mentions-inline.ts +15 -0
- package/src/context-mentions-loader.ts +32 -0
- package/src/context-mentions.ts +16 -0
- package/src/defaults.ts +1 -0
- package/src/generated/runtype-openapi-contract.ts +55 -3
- package/src/index-core.ts +46 -1
- package/src/index-global.ts +51 -0
- package/src/index.ts +8 -0
- package/src/markdown-parsers-loader.test.ts +158 -0
- package/src/markdown-parsers-loader.ts +83 -27
- package/src/plugin-kit.test.ts +40 -0
- package/src/plugin-kit.ts +39 -5
- package/src/runtime/host-layout.test.ts +163 -0
- package/src/runtime/host-layout.ts +110 -7
- package/src/runtime/init.ts +18 -61
- package/src/session.mentions.test.ts +175 -0
- package/src/session.test.ts +52 -4
- package/src/session.ts +197 -27
- package/src/smart-dom-reader.test.ts +129 -2
- package/src/smart-dom-reader.ts +127 -1
- package/src/styles/context-mention-menu-css.ts +176 -0
- package/src/styles/widget.css +1002 -152
- package/src/theme-editor/preview.ts +2 -0
- package/src/theme-editor/sections.test.ts +26 -1
- package/src/theme-editor/sections.ts +13 -5
- package/src/theme-reference.ts +2 -2
- package/src/tool-call-display-defaults.test.ts +1 -0
- package/src/types/theme.ts +79 -0
- package/src/types.ts +1041 -17
- package/src/ui.artifact-pane-gating.test.ts +636 -0
- package/src/ui.component-directive.test.ts +104 -0
- package/src/ui.composer-bar.test.ts +60 -2
- package/src/ui.detached-panel.test.ts +1049 -0
- package/src/ui.mention-submit.test.ts +235 -0
- package/src/ui.tool-display.test.ts +51 -0
- package/src/ui.ts +998 -159
- package/src/utils/artifact-custom-actions.ts +128 -0
- package/src/utils/artifact-display.test.ts +42 -0
- package/src/utils/artifact-display.ts +84 -0
- package/src/utils/artifact-file.test.ts +116 -0
- package/src/utils/artifact-file.ts +117 -0
- package/src/utils/artifact-gate.test.ts +112 -5
- package/src/utils/artifact-gate.ts +39 -14
- package/src/utils/artifact-loading-status.ts +55 -0
- package/src/utils/artifact-status-label.ts +190 -0
- package/src/utils/buttons.ts +7 -1
- package/src/utils/chunk-loader.test.ts +97 -0
- package/src/utils/chunk-loader.ts +88 -0
- package/src/utils/code-highlight.test.ts +186 -0
- package/src/utils/code-highlight.ts +400 -0
- package/src/utils/composer-contenteditable.test.ts +507 -0
- package/src/utils/composer-contenteditable.ts +626 -0
- package/src/utils/composer-document.test.ts +280 -0
- package/src/utils/composer-document.ts +293 -0
- package/src/utils/composer-history.test.ts +35 -7
- package/src/utils/composer-history.ts +30 -20
- package/src/utils/composer-input.ts +159 -0
- package/src/utils/context-mention-controller.test.ts +1215 -0
- package/src/utils/context-mention-controller.ts +1186 -0
- package/src/utils/context-mention-manager.test.ts +422 -0
- package/src/utils/context-mention-manager.ts +410 -0
- package/src/utils/context-mention-orchestrator.test.ts +538 -0
- package/src/utils/context-mention-orchestrator.ts +348 -0
- package/src/utils/icons.ts +2 -0
- package/src/utils/live-region.test.ts +108 -0
- package/src/utils/live-region.ts +94 -0
- package/src/utils/mention-channels.ts +63 -0
- package/src/utils/mention-llm-format.test.ts +91 -0
- package/src/utils/mention-llm-format.ts +79 -0
- package/src/utils/mention-matcher.test.ts +86 -0
- package/src/utils/mention-matcher.ts +221 -0
- package/src/utils/mention-token.ts +72 -0
- package/src/utils/mention-trigger.test.ts +155 -0
- package/src/utils/mention-trigger.ts +156 -0
- package/src/utils/roving-tablist.test.ts +152 -0
- package/src/utils/roving-tablist.ts +111 -0
- package/src/utils/spinner.ts +45 -0
- package/src/utils/theme.test.ts +76 -4
- package/src/utils/theme.ts +7 -0
- package/src/utils/tokens.ts +118 -11
- package/src/utils/tool-loading-animation.test.ts +32 -0
- package/src/utils/tool-loading-animation.ts +24 -0
- package/dist/chunk-DFBSCFYN.js +0 -1
- package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
- package/dist/session-reconnect-U77QFUR7.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -1,23 +1,37 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[o]);)o++};return s()},
|
|
3
|
-
`),
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Ty=Object.create;var Is=Object.defineProperty;var Ey=Object.getOwnPropertyDescriptor;var ky=Object.getOwnPropertyNames;var Ly=Object.getPrototypeOf,Py=Object.prototype.hasOwnProperty;var Aa=(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 Ry=(e,t)=>()=>(e&&(t=e(e=0)),t);var gf=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hf=(e,t)=>{for(var n in t)Is(e,n,{get:t[n],enumerable:!0})},yf=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ky(t))!Py.call(e,r)&&r!==n&&Is(e,r,{get:()=>t[r],enumerable:!(o=Ey(t,r))||o.enumerable});return e};var po=(e,t,n)=>(n=e!=null?Ty(Ly(e)):{},yf(t||!e||!e.__esModule?Is(n,"default",{value:e,enumerable:!0}):n,e)),Iy=e=>yf(Is({},"__esModule",{value:!0}),e);var jl=gf(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.Allow=ge.ALL=ge.COLLECTION=ge.ATOM=ge.SPECIAL=ge.INF=ge._INFINITY=ge.INFINITY=ge.NAN=ge.BOOL=ge.NULL=ge.OBJ=ge.ARR=ge.NUM=ge.STR=void 0;ge.STR=1;ge.NUM=2;ge.ARR=4;ge.OBJ=8;ge.NULL=16;ge.BOOL=32;ge.NAN=64;ge.INFINITY=128;ge._INFINITY=256;ge.INF=ge.INFINITY|ge._INFINITY;ge.SPECIAL=ge.NULL|ge.BOOL|ge.INF|ge.NAN;ge.ATOM=ge.STR|ge.NUM|ge.SPECIAL;ge.COLLECTION=ge.ARR|ge.OBJ;ge.ALL=ge.ATOM|ge.COLLECTION;ge.Allow={STR:ge.STR,NUM:ge.NUM,ARR:ge.ARR,OBJ:ge.OBJ,NULL:ge.NULL,BOOL:ge.BOOL,NAN:ge.NAN,INFINITY:ge.INFINITY,_INFINITY:ge._INFINITY,INF:ge.INF,SPECIAL:ge.SPECIAL,ATOM:ge.ATOM,COLLECTION:ge.COLLECTION,ALL:ge.ALL};ge.default=ge.Allow});var Os=gf(Ut=>{"use strict";var Zy=Ut&&Ut.__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]})),ex=Ut&&Ut.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Zy(t,e,n)};Object.defineProperty(Ut,"__esModule",{value:!0});Ut.Allow=Ut.MalformedJSON=Ut.PartialJSON=Ut.parseJSON=Ut.parse=void 0;var Xt=jl();Object.defineProperty(Ut,"Allow",{enumerable:!0,get:function(){return Xt.Allow}});ex(jl(),Ut);var Fs=class extends Error{};Ut.PartialJSON=Fs;var Ns=class extends Error{};Ut.MalformedJSON=Ns;function Hf(e,t=Xt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return tx(e.trim(),t)}Ut.parseJSON=Hf;var tx=(e,t)=>{let n=e.length,o=0,r=g=>{throw new Fs(`${g} at position ${o}`)},a=g=>{throw new Ns(`${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"||Xt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Xt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Xt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Xt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Xt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Xt.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(Xt.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&&Xt.Allow.OBJ&t)return g;let f=l();u(),o++;try{let h=s();g[f]=h}catch(h){if(Xt.Allow.OBJ&t)return g;throw h}u(),e[o]===","&&o++}}catch{if(Xt.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(Xt.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(Xt.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&&!(Xt.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()},nx=Hf;Ut.parse=nx});var gm={};hf(gm,{createReconnectController:()=>qx});function qx(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(S=>{n=S,o=setTimeout(()=>{o=null,n=null,S()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,d(),e.setAbortController(null);let S=!1;for(let k of e.getMessages())k.streaming&&(k.streaming=!1,S=!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()}):S&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Ux,S=e.config.reconnect?.maxAttempts??h.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<S;){t+=1,e.setStatus("resuming");let k=e.getResumable(),M=k.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:k,attempt:t});let w=null;try{let T=await E({executionId:k.executionId,after:k.lastEventId,signal:A.signal});T&&T.ok&&T.body&&(w=T.body)}catch{w=null}if(A.signal.aborted)return;if(w){let T=e.getMessages().find(b=>b.id===k.assistantMessageId)?.content,R=typeof T=="string"?T:"";try{await e.resumeConnect(w,k.assistantMessageId,R)}catch{}if(A.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<S&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.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 Ux,hm=Ry(()=>{"use strict";Ux=[1e3,2e3,4e3,8e3,8e3]});var gw={};hf(gw,{ASK_USER_QUESTION_CLIENT_TOOL:()=>nd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>td,ASK_USER_QUESTION_TOOL_NAME:()=>ka,AgentWidgetClient:()=>Zo,AgentWidgetSession:()=>Hr,AttachmentManager:()=>nr,BrowserSpeechEngine:()=>Co,DEFAULT_COMPONENTS:()=>ip,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>yi,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>pn,DEFAULT_PALETTE:()=>ap,DEFAULT_SEMANTIC:()=>sp,DEFAULT_WIDGET_CONFIG:()=>pt,PRESETS:()=>nu,PRESET_FULLSCREEN:()=>tu,PRESET_MINIMAL:()=>eu,PRESET_SHOP:()=>Zp,ReadAloudController:()=>tr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Vs,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Yl,SUGGEST_REPLIES_TOOL_NAME:()=>En,THEME_ZONES:()=>Rm,VERSION:()=>Yo,WEBMCP_TOOL_PREFIX:()=>Tn,WebMcpBridge:()=>Er,accessibilityPlugin:()=>xh,animationsPlugin:()=>bh,applyThemeVariables:()=>or,attachHeaderToContainer:()=>sr,brandPlugin:()=>vh,buildComposer:()=>Vr,buildDefaultHeader:()=>wp,buildHeader:()=>Qn,buildHeaderWithLayout:()=>qr,buildMinimalHeader:()=>Ap,builtInClientToolsForDispatch:()=>Rr,collectEnrichedPageContext:()=>hh,componentRegistry:()=>kn,createActionManager:()=>os,createAgentExperience:()=>rl,createAskUserQuestionBubble:()=>Kf,createBestAvailableVoiceProvider:()=>ri,createBubbleWithLayout:()=>vg,createCSATFeedback:()=>tl,createComboButton:()=>Ei,createComponentMiddleware:()=>jg,createComponentStreamParser:()=>Yi,createDefaultSanitizer:()=>Vl,createDirectivePostprocessor:()=>wf,createDropdownMenu:()=>To,createFlexibleJsonStreamParser:()=>Yf,createIconButton:()=>kt,createImagePart:()=>am,createJsonStreamParser:()=>Qs,createLabelButton:()=>Jn,createLocalStorageAdapter:()=>Qi,createMarkdownProcessor:()=>Ma,createMarkdownProcessorFromConfig:()=>Xo,createMessageActions:()=>Pp,createNPSFeedback:()=>nl,createPlainTextParser:()=>Xs,createPlugin:()=>Ah,createRegexJsonParser:()=>Js,createSlashCommandsSource:()=>ah,createStandardBubble:()=>zr,createStaticMentionSource:()=>rh,createTextPart:()=>bo,createTheme:()=>Wr,createThemeObserver:()=>Dr,createToggleGroup:()=>Or,createTypingIndicator:()=>ir,createVoiceProvider:()=>vo,createWidgetHostLayout:()=>as,createXmlParser:()=>Ys,defaultActionHandlers:()=>pr,defaultJsonActionParser:()=>ns,defaultMentionFilter:()=>sl,defaultParseRules:()=>Qp,detectColorScheme:()=>Oa,directivePostprocessor:()=>Af,ensureAskUserQuestionSheet:()=>Pr,escapeHtml:()=>Bn,extractComponentDirectiveFromMessage:()=>el,fileToImagePart:()=>sm,formatEnrichedContext:()=>yh,generateAssistantMessageId:()=>xo,generateMessageId:()=>tm,generateStableSelector:()=>Yp,generateUserMessageId:()=>Ir,getActiveTheme:()=>wo,getColorScheme:()=>Ai,getDisplayText:()=>om,getHeaderLayout:()=>Sp,getImageParts:()=>rm,getPreset:()=>Mh,hasComponentDirective:()=>rs,hasImages:()=>ti,headerLayouts:()=>Ui,highContrastPlugin:()=>wh,initAgentWidget:()=>nh,isAskUserQuestionMessage:()=>jn,isComponentDirectiveType:()=>$g,isDockedMountMode:()=>It,isSuggestRepliesMessage:()=>Pa,isVoiceSupported:()=>Wa,isWebMcpToolName:()=>uo,latestAgentSuggestions:()=>zs,listRegisteredStreamAnimations:()=>bp,loadMarkdownParsers:()=>Sa,markdownPostprocessor:()=>ql,mergeWithDefaults:()=>xi,normalizeContent:()=>nm,onMarkdownParsersReady:()=>Mr,parseAskUserQuestionPayload:()=>Gn,parseSuggestRepliesPayload:()=>ed,pickBestVoice:()=>Br,pluginRegistry:()=>ts,reducedMotionPlugin:()=>Ch,registerStreamAnimationPlugin:()=>ar,removeAskUserQuestionSheet:()=>go,renderComponentDirective:()=>Zi,renderLoadingIndicatorWithFallback:()=>Lp,renderLucideIcon:()=>ne,resolveDockConfig:()=>on,resolveSanitizer:()=>Tr,resolveTokens:()=>Ci,stripWebMcpPrefix:()=>Ws,themeToCssVariables:()=>wi,unregisterStreamAnimationPlugin:()=>xp,validateImageFile:()=>im,validateTheme:()=>lp});var Sr=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:By,load:Hy,provide:ww,getSync:Ul}=Sr({fallbackImport:()=>import("./markdown-parsers-entry")}),Bs=new Set,Wy=()=>{let e=[...Bs];Bs.clear();for(let t of e)try{t()}catch{}},xf=By,Sa=()=>{let e=Ul();return e?Promise.resolve(e):Hy().then(t=>(Wy(),t))},Mr=e=>Ul()?()=>{}:(Bs.add(e),Sa().catch(()=>{}),()=>{Bs.delete(e)});var zn=Ul;var Dy=e=>{if(e)return e},Ma=e=>{let t=null;return n=>{let o=zn();if(!o)return Bn(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=Dy(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},Xo=e=>e?Ma({markedOptions:e.options,renderer:e.renderer}):Ma(),Fy=Ma(),ql=e=>Fy(e),Bn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),vf=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),bf=e=>`%%FORM_PLACEHOLDER_${e}%%`,Cf=(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=bf(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=bf(t.length);return t.push({token:a,type:r}),a}),n},wf=e=>{let t=Xo(e);return n=>{let o=[],r=Cf(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}},Af=e=>{let t=[],n=Cf(e,t),o=ql(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 Ny={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"]},Oy=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Vl=()=>{let e=null;return t=>{let n=zn();if(!n)return Bn(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:")&&!Oy.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,Ny)}},Tr=e=>e===!1?null:typeof e=="function"?e:Vl();var Sf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Mf=e=>e.includes("|"),Tf=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())},_y=e=>`| ${e.join(" | ")} |`,Uy=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,qy=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ef=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(!Mf(r)||Sf.test(r)||!Sf.test(a))continue;let s=Tf(r).length;if(s<1)continue;let l=Uy(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()===""||!Mf(c))break;let d=_y(qy(Tf(c),s));t[p]!==d&&(t[p]=d,n=!0)}o=p-1}return n?t.join(`
|
|
4
|
+
`):e};var Tn="webmcp:",zl=new Map,kf=e=>{zl.clear();for(let t of e){let n=t.title?.trim();n&&zl.set(t.name,n)}},Ta=e=>zl.get(Ws(e)),Hs={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$l=null,Pf=e=>{$l=e};function Rf(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}:${Vy(t.join(""))}`}function Lf(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 Vy(e){let t=Lf(e,0).toString(36),n=Lf(e,2654435761).toString(36);return`${t}.${n}`}var Er=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 Hs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}kf(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=$y(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Mn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return Mn(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=Ws(t),s;try{s=await r.getTools()}catch(h){let S=h instanceof Error?h.message:String(h);return Mn(`Failed to read WebMCP registry: ${S}`)}kf(s);let l=s.find(h=>h.name===a);if(!l)return Mn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Mn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Mn("Aborted by cancel()");let p=Ta(a),c={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Mn("User declined the tool call.");if(o?.aborted)return Mn("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,Xy(n),{signal:d.signal});return jy(h)}catch(h){if(u)return Mn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Mn("Aborted by cancel()");let S=h instanceof Error?h.message:String(h);return Mn(S)}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}($l?await $l():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Hs.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,Hs.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??Gy;try{return await n(t)}catch(o){return Hs.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=>zy(t,o))}},Ws=e=>e.startsWith(Tn)?e.slice(Tn.length):e,uo=e=>e.startsWith(Tn),zy=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},$y=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},jy=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:Jy(t)}]}},Mn=e=>({isError:!0,content:[{type:"text",text:e}]}),Gy=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Ky(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(r)},wb=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)}},Cb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Sb=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Ab="agent_",Mb="flow_";function rh(e){return e.startsWith(Ab)?{kind:"agentId",agentId:e}:e.startsWith(Mb)?{kind:"flowId",flowId:e}:null}function oh(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let d=rh(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)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:c(i).payload}}let n=rh(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var En=Ia(li(),1);var v=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Tt=(e,t={},...r)=>{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 i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},bs=(...e)=>e.filter(Boolean).join(" ");var ws="ask_user_question",vs=8,Da="data-persona-ask-sheet-for",Pb="Other",Rb="Other\u2026",sh="Type your own answer here",ih="Send",Ib="Next",Wb="Back",Hb="Submit all",Bb="Skip",Db=3,$l="data-ask-current-index",jl="data-ask-question-count",lh="data-ask-answers",Gl="data-ask-grouped",dh="data-ask-layout",Fb=e=>e.layout==="pills"?"pills":"rows",Nb=e=>e.getAttribute(dh)==="pills"?"pills":"rows",ah=!1,ch=e=>e.replace(/["\\]/g,"\\$&"),en=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ws,di=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},tn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,En.parse)(n,En.STR|En.OBJ|En.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},Cs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>vs&&!ah&&(ah=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${vs}.`)),t.slice(0,vs)},Ob=e=>{var t;return(t=Cs(e)[0])!=null?t:null},_b=(e,t)=>{var r;return(r=Cs(e)[t])!=null?r:null},ph=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},uh=(e,t,r)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=v("span","persona-ask-row-check");o.appendChild(n)}else{let n=v("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Ub=(e,t,r,o)=>{let a=v("button",r==="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),r==="rows"){let s=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=uh(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},qb=e=>{let r=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 r.setAttribute("aria-hidden","true"),r},Vb=(e,t,r,o)=>{var p,m,g;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!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(c.length===0&&!r){for(let u=0;u<Db;u++)a.appendChild(qb(o));return a}if(c.forEach((u,h)=>{a.appendChild(Ub(u,h,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let u=o==="rows"?Pb:Rb;if(o==="rows"){let h=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");h.setAttribute("data-ask-user-action","focus-free-text"),h.setAttribute("data-option-index",String(c.length)),h.setAttribute("data-ask-other-row","true");let y=v("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:sh,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:u),y.appendChild(E),h.appendChild(y);let T=uh(o,s,c.length);T&&h.appendChild(T),a.appendChild(h)}else{let h=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");h.type="button",h.setAttribute("data-ask-user-action","open-free-text"),h.textContent=(g=t.freeTextLabel)!=null?g:u,a.appendChild(h)}}return a},fh=(e,t)=>{var a,s;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 n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:sh,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:ih,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},zb=e=>{var o;let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=v("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:ih,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},$b=(e,t,r)=>{var d,p,m,g;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 n=v("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:Wb,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);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=(p=r.skipLabel)!=null?p:Bb,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(m=r.submitAllLabel)!=null?m:Hb:(g=r.nextLabel)!=null?g:Ib,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},sa=e=>{let t=e.getAttribute(lh);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},mh=(e,t)=>{e.setAttribute(lh,JSON.stringify(t))},ao=e=>{var r;let t=Number((r=e.getAttribute($l))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},jb=(e,t)=>{e.setAttribute($l,String(Math.max(0,Math.floor(t))))},Fa=e=>{var r;let t=Number((r=e.getAttribute(jl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},kn=e=>e.getAttribute(Gl)==="true",Gb=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Kb=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},ci=(e,t)=>{let{payload:r}=tn(t),o=Cs(r),n=sa(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},gh=e=>{let t=sa(e),r=ao(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var m;let d=(m=c.getAttribute("data-option-label"))!=null?m:"",p=n.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},hh=e=>{if(!kn(e))return;let t=sa(e),r=ao(e),o=t[r],n=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=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Kl=(e,t,r)=>{let o=di(r),n=Nb(e),{payload:a,complete:s}=tn(t),i=kn(e),c=ao(e),d=Fa(e),p=i?_b(a,c):Ob(a),m=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${c+1}/${d}`:"");let u=e.querySelector('[data-ask-stepper="true"]');u&&u.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";h.textContent=A,h.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let y=e.querySelector('[data-ask-pill-list="true"]');if(y){let A=Vb(p,o,s,n);y.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(fh(o,n))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!E?e.appendChild(zb(o)):(!m||i)&&E&&E.remove(),e.setAttribute("data-multi-select",m?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=$b(c,d,o);T?T.replaceWith(A):e.appendChild(A)}else T&&T.remove();gh(e),hh(e)},Xb=(e,t,r)=>{let o=di(t),n=Fb(o),a=e.toolCall.id,s=Cs(r),i=Math.max(1,s.length),c=i>1,d=Gb(e,s),p=c?Kb(e,i):0,m=v("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Da,a),m.setAttribute("data-tool-call-id",a),m.setAttribute("data-message-id",e.id),m.setAttribute(jl,String(i)),m.setAttribute($l,String(p)),m.setAttribute(Gl,c?"true":"false"),m.setAttribute(dh,n),mh(m,d),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),ph(m,o);let g=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=v("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let h=v("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),m.appendChild(g);let E=v("div",n==="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"),m.appendChild(E),n!=="rows"&&m.appendChild(fh(o,n)),Kl(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Qb=(e,t,r)=>{let{payload:o}=tn(t),n=Math.max(1,Cs(o).length);n>Fa(e)&&(e.setAttribute(jl,String(n)),n>1&&!kn(e)&&e.setAttribute(Gl,"true")),Kl(e,t,r)},xh=(e,t)=>{let r=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=di(t);ph(r,o);let n=v("span","persona-ask-stub-label"),{complete:a}=tn(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Na=(e,t,r)=>{if(!r||!en(e)||di(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Da}]`).forEach(d=>{d.getAttribute(Da)!==n&&d.remove()});let s=r.querySelector(`[${Da}="${ch(n)}"]`);if(s){Qb(s,e,t);return}let{payload:i}=tn(e),c=Xb(e,t,i);r.appendChild(c)},Ln=(e,t)=>{if(!e)return;let r=t?`[${Da}="${ch(t)}"]`:`[${Da}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Xl=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),Pn=(e,t)=>{let r=sa(e),o=ao(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,mh(e,r),gh(e),hh(e)},pi=(e,t,r,o)=>{let n=Fa(e),a=Math.max(0,Math.min(n-1,o));jb(e,a),Kl(e,t,r)};var bo="suggest_replies";var Ql={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},ui={name:bo,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:Ql,origin:"sdk",annotations:{readOnlyHint:!0}},Jl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===bo},Yl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.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},fi=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!Ss(o))continue;let n=Yl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},yh=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Zl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:vs,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},ed={name:ws,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:Zl,origin:"sdk",annotations:{readOnlyHint:!0}},Oa=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(ed),yh(e)&&t.push(ui),t};var rn=Ia(li(),1),mi=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ts=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},yi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},bi=()=>{var t;let e=Zb();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},vi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,rn.parse)(r,rn.STR|rn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?mi(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=mi(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},wh=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?mi(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?mi(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<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,rn.parse)(a,rn.STR|rn.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},wi=()=>{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 Ch="4.7.0";var ia=Ch;var tv="https://api.runtype.com/v1/dispatch",Ci="https://api.runtype.com";function rv(e){var a,s;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 n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var rd=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 ov(e){switch(e){case"json":return vi;case"regex-json":return bi;case"xml":return wi;default:return yi}}var Sh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nv(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Sh(r);if(!Sh(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=Ts(e);return Ts(t)!==null&&s===null?t:e}var la=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;var r,o,n,a;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=(r=t.apiUrl)!=null?r:tv,this.headers={"Content-Type":"application/json","X-Persona-Version":ia,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:ov(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ba(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=oh(o,n);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){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ci}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,d;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(d=r.agentId)!=null?d:r.flowId,n={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":ia},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ci}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ia},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){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:r})}async submitCSATFeedback(t,r){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:r})}async submitNPSFeedback(t,r){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:r})}async dispatch(t,r){var o;return(o=t.signal)==null||o.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,n,a,s;r({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),(n=(o=this.config).onSessionExpired)==null||n.call(o);let u=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:u}),u}let c=await this.buildPayload(t.messages),d=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([u])=>u!=="sessionId"&&u!=="session_id")):void 0,p={sessionId:i.sessionId,messages:t.messages.filter(rd).map(u=>{var h,y,E;return{id:u.id,role:u.role,content:(E=(y=(h=u.contentParts)!=null?h:u.llmContent)!=null?y:u.rawContent)!=null?E:u.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},{response:m,commit:g}=await this.sendWithClientToolsDiff(i.sessionId,c.clientTools,u=>{let h={...p,...u};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",h),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ia},body:JSON.stringify(h),signal:t.signal})});if(!m.ok){let u=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clearClientSession(),(s=(a=this.config).onSessionExpired)==null||s.call(a);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(u.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let h=new Error(u.error||"Failed to send message");throw r({type:"error",error:h}),h}if(!m.body){let u=new Error("No response body received");throw r({type:"error",error:u}),u}g(),r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(i){let c=i instanceof Error?i:new Error(String(i));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){r({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let n={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();n={...n,...s}}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let i=s instanceof Error?s:new Error(String(s));throw r({type:"error",error:i}),i}else a=await fetch(this.apiUrl,{method:"POST",headers:n,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 r({type:"error",error:s}),s}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let n={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();n={...n,...s}}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:n,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let i=s instanceof Error?s:new Error(String(s));throw r({type:"error",error:i}),i}else a=await fetch(this.apiUrl,{method:"POST",headers:n,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 r({type:"error",error:s}),s}r({type:"status",status:"connected"});try{await this.streamResponse(a.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o,n){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ci}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async sendWithClientToolsDiff(t,r,o,n){let a=!!(r&&r.length>0),s=a?th(r):void 0,i=this.clientToolsFingerprintSessionId===t,c=a&&i&&this.lastSentClientToolsFingerprint===s,d=!a&&(n==null?void 0:n.emptyMeansReplace)===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let g=0;;g++){if(m=await o({...a&&(p||!c)&&r?{clientTools:r}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),m.status===409&&g===0&&a){let h=await m.clone().json().catch(()=>null);if((h==null?void 0:h.error)==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=s!=null?s:null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,r,o){var d,p,m,g;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||Ci}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};if(s&&(c.sessionId=s),n&&s){let u=[...Oa(this.config),...(g=await((m=this.webMcpBridge)==null?void 0:m.snapshotForDispatch()))!=null?g:[]],{response:h,commit:y}=await this.sendWithClientToolsDiff(s,u,E=>{let T={...c,...E};return this.debug&&console.debug("[AgentWidgetClient] client token resume",T),fetch(a,{method:"POST",headers:i,body:JSON.stringify(T),signal:o==null?void 0:o.signal})},{emptyMeansReplace:!0});return h.ok&&y(),h}return fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(rd).filter(d=>d.role==="user"||d.role==="assistant"||d.role==="system").filter(d=>!d.variant||d.variant==="assistant").sort((d,p)=>{let m=new Date(d.createdAt).getTime(),g=new Date(p.createdAt).getTime();return m-g}).map(d=>{var p,m,g;return{role:d.role,content:(g=(m=(p=d.contentParts)!=null?p:d.llmContent)!=null?m:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Oa(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async p=>{try{let m=await p({messages:t,config:this.config});m&&typeof m=="object"&&Object.assign(d,m)}catch(m){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",m)}})),Object.keys(d).length&&(n.context=d)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(rd).sort((c,d)=>{let p=new Date(c.createdAt).getTime(),m=new Date(d.createdAt).getTime();return p-m}).map(c=>{var d,p,m;return{role:c.role,content:(m=(p=(d=c.contentParts)!=null?d:c.llmContent)!=null?p:c.rawContent)!=null?m:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,d]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=d);let a=[...Oa(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async d=>{try{let p=await d({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let d=c;return n.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=n.clientTools),d}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=m,n(m),m},d=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=d(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o,n){var br,wo,Co,Ve;let a=t.getReader(),s=new TextDecoder,i="",c=Date.now(),d=0,p=()=>c+d++,m=H=>{let ce=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Se=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Ae=H.tools?H.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...H,reasoning:ce,toolCall:Se,tools:Ae}},g=H=>{if(H.role!=="assistant"||H.variant)return!0;let ce=Array.isArray(H.contentParts)&&H.contentParts.length>0,Se=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||ce||Se||!!H.stopReason},u=H=>{g(H)&&r({type:"message",message:m(H)})},h=null,y=null,E={current:null},T={current:null},A=null,k="",w=new Map,C=new Map,S=new Map,M=new Map,W=new Map,I={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},D=H=>{if(H==null)return null;try{return String(H)}catch{return null}},O=H=>{var ce,Se,Ae,Ie,et;return D((et=(Ie=(Ae=(Se=(ce=H.stepId)!=null?ce:H.step_id)!=null?Se:H.step)!=null?Ae:H.parentId)!=null?Ie:H.flowStepId)!=null?et:H.flow_step_id)},Q=H=>{var ce,Se,Ae,Ie,et,Qe,gt;return D((gt=(Qe=(et=(Ie=(Ae=(Se=(ce=H.callId)!=null?ce:H.call_id)!=null?Se:H.requestId)!=null?Ae:H.request_id)!=null?Ie:H.toolCallId)!=null?et:H.tool_call_id)!=null?Qe:H.stepId)!=null?gt:H.step_id)},me=o,ue=!1,Z=()=>{if(h)return h;let H,ce="",Se=A;return!ue&&me?(H=me,ue=!0,ce=n!=null?n:""):me&&Se?H=`${me}_${Se}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:H,role:"assistant",content:ce,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},u(h),h},Le=(H,ce)=>{I.lastId=ce,H&&I.byStep.set(H,ce)},He=(H,ce)=>{var et;let Se=(et=H.reasoningId)!=null?et:H.id,Ae=O(H);if(Se){let Qe=String(Se);return Le(Ae,Qe),Qe}if(Ae){let Qe=I.byStep.get(Ae);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!ce)return I.lastId;if(!ce)return null;let Ie=`reason-${p()}`;return Le(Ae,Ie),Ie},ie=H=>{let ce=M.get(H);if(ce)return ce;let Se={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:H,status:"streaming",chunks:[]}};return M.set(H,Se),u(Se),Se},Me=(H,ce)=>{R.lastId=ce,H&&R.byCall.set(H,ce)},oe=new Set,se=new Map,ge=new Set,Te=new Map,qe=H=>{if(!H)return!1;let ce=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return ce==="emit_artifact_markdown"||ce==="emit_artifact_component"},j=(H,ce)=>{var et;let Se=(et=H.toolId)!=null?et:H.id,Ae=Q(H);if(Se){let Qe=String(Se);return Me(Ae,Qe),Qe}if(Ae){let Qe=R.byCall.get(Ae);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ce)return R.lastId;if(!ce)return null;let Ie=`tool-${p()}`;return Me(Ae,Ie),Ie},ee=H=>{let ce=W.get(H);if(ce)return ce;let Se={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:H,status:"pending"}};return W.set(H,Se),u(Se),Se},Ee=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let ce=Number(H);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let Se=Date.parse(H);if(!Number.isNaN(Se))return Se}return Date.now()},te=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},le=new Map,ke=new Map,nt=new Map,yt=(H,ce,Se)=>{var gt;let Ae=nt.get(H);Ae||(Ae=[],nt.set(H,Ae));let Ie=0,et=Ae.length;for(;Ie<et;){let pe=Ie+et>>>1;Ae[pe].seq<ce?Ie=pe+1:et=pe}((gt=Ae[Ie])==null?void 0:gt.seq)===ce?Ae[Ie]={seq:ce,text:Se}:Ae.splice(Ie,0,{seq:ce,text:Se});let Qe="";for(let pe=0;pe<Ae.length;pe++)Qe+=Ae[pe].text;return Qe},Kt=(H,ce)=>{let Se=te(ce),Ae=ke.get(H.id),Ie=nv(Ae,Se);H.rawContent=Ie;let et=le.get(H.id),Qe=ae=>{var Ke;let mt=(Ke=H.content)!=null?Ke:"";ae.trim()!==""&&(mt.trim().length===0||ae.startsWith(mt)||ae.trimStart().startsWith(mt.trim()))&&(H.content=ae)},gt=()=>{var ae;if(et){let mt=(ae=et.close)==null?void 0:ae.call(et);mt instanceof Promise&&mt.catch(()=>{})}le.delete(H.id),ke.delete(H.id),H.streaming=!1,u(H)};if(!et){Qe(Se),gt();return}let pe=Ts(Ie);if(pe!==null&&pe.trim()!==""){Qe(pe),gt();return}let N=ae=>{var Lt;let mt=typeof ae=="string"?ae:(Lt=ae==null?void 0:ae.text)!=null?Lt:null;if(mt!==null&&mt.trim()!=="")return mt;let Ke=et.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Se},ye;try{ye=et.processChunk(Ie)}catch{Qe(Se),gt();return}if(ye instanceof Promise){ye.then(ae=>{Qe(N(ae)),gt()}).catch(()=>{Qe(Se),gt()});return}Qe(N(ye)),gt()},jt=null,ct=(H,ce,Se,Ae)=>{var pe;H.rawContent=ce,le.has(H.id)||le.set(H.id,this.createStreamParser());let Ie=le.get(H.id),et=ce.trim().startsWith("{")||ce.trim().startsWith("[");if(et&&ke.set(H.id,ce),Ie.__isPlainTextParser===!0){H.content=Ae!==void 0?ce:H.content+Se,ke.delete(H.id),le.delete(H.id),H.rawContent=void 0,u(H);return}let gt=Ie.processChunk(ce);if(gt instanceof Promise)gt.then(N=>{var ae;let ye=typeof N=="string"?N:(ae=N==null?void 0:N.text)!=null?ae:null;ye!==null&&ye.trim()!==""?(H.content=ye,u(H)):!et&&!ce.trim().startsWith("<")&&(H.content=Ae!==void 0?ce:H.content+Se,ke.delete(H.id),le.delete(H.id),H.rawContent=void 0,u(H))}).catch(()=>{H.content=Ae!==void 0?ce:H.content+Se,ke.delete(H.id),le.delete(H.id),H.rawContent=void 0,u(H)});else{let N=typeof gt=="string"?gt:(pe=gt==null?void 0:gt.text)!=null?pe:null;N!==null&&N.trim()!==""?(H.content=N,u(H)):!et&&!ce.trim().startsWith("<")&&(H.content=Ae!==void 0?ce:H.content+Se,ke.delete(H.id),le.delete(H.id),H.rawContent=void 0,u(H))}},fe=(H,ce)=>{var pe,N;let Se=ce!=null?ce:H.content;if(Se==null||Se===""){H.streaming=!1,u(H);return}let Ae=ke.get(H.id),Ie=Ae!=null?Ae:te(Se);H.rawContent=Ie;let et=le.get(H.id),Qe=null,gt=!1;if(et&&(Qe=et.getExtractedText(),Qe===null&&(Qe=Ts(Ie)),Qe===null)){let ye=et.processChunk(Ie);ye instanceof Promise?(gt=!0,ye.then(ae=>{var Ke;let mt=typeof ae=="string"?ae:(Ke=ae==null?void 0:ae.text)!=null?Ke:null;mt!==null&&(H.content=mt,H.streaming=!1,le.delete(H.id),ke.delete(H.id),u(H))}).catch(()=>{})):Qe=typeof ye=="string"?ye:(pe=ye==null?void 0:ye.text)!=null?pe:null}if(!gt){Qe!==null&&Qe.trim()!==""?H.content=Qe:ke.has(H.id)||(H.content=te(Se));let ye=le.get(H.id);if(ye){let ae=(N=ye.close)==null?void 0:N.call(ye);ae instanceof Promise&&ae.catch(()=>{}),le.delete(H.id)}ke.delete(H.id),H.streaming=!1,u(H)}},X=(H,ce,Se)=>{let Ae=C.get(H);if(Ae)return Ae;let Ie={id:`nested-${ce}-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:H,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ce}};return C.set(H,Ie),u(Ie),Ie},st=[],je,Ce=new Map,ve=0,Ye="agent",Vt=!1,xe=null,de=null,Ar=new Map,Ct=(br=this.config.iterationDisplay)!=null?br:"separate";for(je=()=>{var H,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,er,So,Uo,io,lo,sn,zt,co,qo,Fr,Wr,Nr,po,Ao,ln,Qr,dn,St,Mo,To,Vo,uo,ht,Un,Eo,qn,Hr,ba,cn,zo,pn,un,Vn,zn,fn,vt,Or,_r,Mr,At,Jr,Yr,Ur,mn,we,$o,Zr,Nt,eo,jo,rs,va,os,$n,ko,gn,it,nr,ar,Lo,ns,Go,jn,Po,q,wa,to,Ro,Ko,Io,fo,Ca,Xs,vr,Tr,mo,Er,Gn,go,wr,Wo,Sa,Kn,Aa,hn;for(let xn=0;xn<st.length;xn++){let rt=st[xn].payloadType,L=st[xn].payload;if(!Vt&&Ye!=="flow"&&typeof L.stepType=="string"&&(Ye="flow"),rt==="reasoning_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){w.set($,z),X($,z,"reasoning");continue}let K=(H=He(L,!0))!=null?H:`reason-${p()}`,G=ie(K);G.reasoning=(ce=G.reasoning)!=null?ce:{id:K,status:"streaming",chunks:[]},G.reasoning.startedAt=(Ae=G.reasoning.startedAt)!=null?Ae:Ee((Se=L.startedAt)!=null?Se:L.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),G.streaming=!0,G.reasoning.status="streaming",u(G)}else if(rt==="reasoning_delta"){let $=typeof L.id=="string"?L.id:null;if($&&w.has($)&&C.has($)){let De=C.get($),tt=(Qe=(et=(Ie=L.reasoningText)!=null?Ie:L.text)!=null?et:L.delta)!=null?Qe:"";tt&&L.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(tt)),u(De));continue}let z=(pe=(gt=He(L,!1))!=null?gt:He(L,!0))!=null?pe:`reason-${p()}`,K=ie(z);K.reasoning=(N=K.reasoning)!=null?N:{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=(ae=K.reasoning.startedAt)!=null?ae:Ee((ye=L.startedAt)!=null?ye:L.timestamp);let G=(Lt=(Ke=(mt=L.reasoningText)!=null?mt:L.text)!=null?Ke:L.delta)!=null?Lt:"";if(G&&L.hidden!==!0){let De=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(De!==void 0){let tt=yt(z,De,String(G));K.reasoning.chunks=[tt]}else K.reasoning.chunks.push(String(G))}if(K.reasoning.status=L.done?"complete":"streaming",L.done){K.reasoning.completedAt=Ee((Et=L.completedAt)!=null?Et:L.timestamp);let De=(bt=K.reasoning.startedAt)!=null?bt:Date.now();K.reasoning.durationMs=Math.max(0,((It=K.reasoning.completedAt)!=null?It:Date.now())-De)}K.streaming=K.reasoning.status!=="complete",u(K)}else if(rt==="reasoning_complete"){let $=typeof L.id=="string"?L.id:null;if($&&w.has($)&&C.has($)){let tt=C.get($);if(tt.reasoning){let lt=typeof L.text=="string"?L.text:"";lt&&tt.reasoning.chunks.length===0&&tt.reasoning.chunks.push(lt),tt.reasoning.status="complete",tt.streaming=!1,u(tt)}w.delete($),C.delete($);continue}let z=(Ft=(Qt=He(L,!1))!=null?Qt:He(L,!0))!=null?Ft:`reason-${p()}`,K=typeof L.text=="string"?L.text:"";!M.get(z)&&(K||L.scope==="loop")&&ie(z);let G=M.get(z);if(G!=null&&G.reasoning){(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),K&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(K),G.reasoning.status="complete",G.reasoning.completedAt=Ee((er=L.completedAt)!=null?er:L.timestamp);let tt=(So=G.reasoning.startedAt)!=null?So:Date.now();G.reasoning.durationMs=Math.max(0,((Uo=G.reasoning.completedAt)!=null?Uo:Date.now())-tt),G.streaming=!1,u(G)}let De=O(L);De&&I.byStep.delete(De)}else if(rt==="tool_start"){h&&(h.streaming=!1,u(h),h=null),typeof L.iteration=="number"&&(ve=L.iteration);let $=(lo=(io=typeof L.toolCallId=="string"?L.toolCallId:void 0)!=null?io:j(L,!0))!=null?lo:`tool-${p()}`,z=(sn=L.toolName)!=null?sn:L.name;if(qe(z)){oe.add($);continue}Me(Q(L),$);let K=ee($),G=(zt=K.toolCall)!=null?zt:{id:$,status:"pending"};G.name=z!=null?z:G.name,G.status="running",L.parameters!==void 0?G.args=L.parameters:L.args!==void 0&&(G.args=L.args),G.startedAt=(qo=G.startedAt)!=null?qo:Ee((co=L.startedAt)!=null?co:L.timestamp),G.completedAt=void 0,G.durationMs=void 0,K.toolCall=G,K.streaming=!0,L.executionId&&(K.agentMetadata={executionId:L.executionId,iteration:L.iteration}),u(K)}else if(rt==="tool_output_delta"){let $=(Wr=(Fr=j(L,!1))!=null?Fr:j(L,!0))!=null?Wr:`tool-${p()}`;if(oe.has($))continue;let z=ee($),K=(Nr=z.toolCall)!=null?Nr:{id:$,status:"running"};K.startedAt=(Ao=K.startedAt)!=null?Ao:Ee((po=L.startedAt)!=null?po:L.timestamp);let G=(dn=(Qr=(ln=L.text)!=null?ln:L.delta)!=null?Qr:L.message)!=null?dn:"";G&&(K.chunks=(St=K.chunks)!=null?St:[],K.chunks.push(String(G))),K.status="running",z.toolCall=K,z.streaming=!0;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(Vo=z.agentMetadata)!=null?Vo:{executionId:(Mo=De==null?void 0:De.executionId)!=null?Mo:L.executionId,iteration:(To=De==null?void 0:De.iteration)!=null?To:L.iteration}),u(z)}else if(rt==="tool_complete"){let $=(ht=(uo=j(L,!1))!=null?uo:j(L,!0))!=null?ht:`tool-${p()}`;if(oe.has($)){oe.delete($);continue}let z=ee($),K=(Un=z.toolCall)!=null?Un:{id:$,status:"running"};K.status="complete",L.result!==void 0&&(K.result=L.result),typeof L.duration=="number"&&(K.duration=L.duration),K.completedAt=Ee((Eo=L.completedAt)!=null?Eo:L.timestamp);let G=(qn=L.duration)!=null?qn:L.executionTime;if(typeof G=="number")K.durationMs=G;else{let lt=(Hr=K.startedAt)!=null?Hr:Date.now();K.durationMs=Math.max(0,((ba=K.completedAt)!=null?ba:Date.now())-lt)}z.toolCall=K,z.streaming=!1;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(pn=z.agentMetadata)!=null?pn:{executionId:(cn=De==null?void 0:De.executionId)!=null?cn:L.executionId,iteration:(zo=De==null?void 0:De.iteration)!=null?zo:L.iteration}),u(z);let tt=Q(L);tt&&R.byCall.delete(tt)}else if(rt==="await"&&L.toolName){let $=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,z=(un=$!=null?$:L.toolId)!=null?un:`local-${p()}`,K=ee(z),G=L.toolName,De=L.origin==="webmcp"&&!Tn(G)?`webmcp:${G}`:G,tt=Tn(De),lt=(Vn=K.toolCall)!=null?Vn:{id:z,status:"pending"};lt.name=De,lt.args=L.parameters,lt.status=tt?"running":"complete",lt.chunks=(zn=lt.chunks)!=null?zn:[],lt.startedAt=(Or=lt.startedAt)!=null?Or:Ee((vt=(fn=L.startedAt)!=null?fn:L.timestamp)!=null?vt:L.awaitedAt),tt?(lt.completedAt=void 0,lt.duration=void 0,lt.durationMs=void 0):lt.completedAt=(_r=lt.completedAt)!=null?_r:lt.startedAt,K.toolCall=lt,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(At=L.executionId)!=null?At:(Mr=K.agentMetadata)==null?void 0:Mr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(K)}else if(rt==="text_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){w.set($,z);continue}let K=h;K&&(Ye==="flow"?(fe(K),jt=K):(K.streaming=!1,u(K)),h=null),A=typeof L.id=="string"?L.id:A,k=""}else if(rt==="text_delta"){let $=typeof L.id=="string"?L.id:null,z=$?w.get($):void 0;if($&&z){let G=typeof L.delta=="string"?L.delta:"",De=((Jr=S.get($))!=null?Jr:"")+G;if(S.set($,De),De.trim()==="")continue;let tt=X($,z);tt.agentMetadata={...tt.agentMetadata,executionId:L.executionId,parentToolId:z},ct(tt,De,G,void 0);continue}if(A=typeof L.id=="string"?L.id:A,Ye==="flow"){let G=typeof L.delta=="string"?L.delta:"";if(k+=G,k.trim()==="")continue;let De=Z();De.agentMetadata={executionId:L.executionId,iteration:L.iteration},ct(De,k,G,void 0),y=De;continue}let K=Z();K.content+=(Yr=L.delta)!=null?Yr:"",K.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:xe!=null?xe:void 0,agentName:de==null?void 0:de.agentName},y=K,u(K)}else if(rt==="text_complete"){let $=typeof L.id=="string"?L.id:null;if($&&w.has($)){let K=C.get($);K&&fe(K),w.delete($),S.delete($),C.delete($);continue}let z=h;z&&(Ye==="flow"?(fe(z),jt=z):(((Ur=z.content)!=null?Ur:"")===""&&typeof L.text=="string"&&(z.content=L.text),z.streaming=!1,u(z)),h=null),A=null,k=""}else if(rt==="step_complete"){let $=L.stepType,z=L.executionType;if($==="tool"||z==="context")continue;if(L.success===!1){let K=L.error,G=typeof K=="string"&&K!==""?K:K!=null&&typeof K=="object"&&Reflect.has(K,"message")?String((mn=K.message)!=null?mn:"Step failed"):"Step failed";r({type:"error",error:new Error(G)});let De=h;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let K=jt;jt=null;let G=L.stopReason,De=(we=L.result)==null?void 0:we.response;if(K)G&&(K.stopReason=G),De!=null?Kt(K,De):K.streaming!==!1&&(le.delete(K.id),ke.delete(K.id),K.streaming=!1,u(K));else{let tt=De!=null&&De!=="";if(tt||G){let lt=Z();G&&(lt.stopReason=G),tt?fe(lt,De):(lt.streaming=!1,u(lt))}}continue}}else if(rt==="execution_start")Ye=L.kind==="flow"?"flow":"agent",Vt=!0,Ye==="agent"&&(de={executionId:L.executionId,agentId:($o=L.agentId)!=null?$o:"virtual",agentName:(Zr=L.agentName)!=null?Zr:"",status:"running",currentIteration:0,maxTurns:(Nt=L.maxTurns)!=null?Nt:1,startedAt:Ee(L.startedAt)});else if(rt==="turn_start"){let $=typeof L.iteration=="number"?L.iteration:ve;if($!==ve){if(de&&(de.currentIteration=$),Ct==="separate"&&$>1){let z=h;z&&(z.streaming=!1,u(z),Ar.set($-1,z),h=null)}ve=$}xe=typeof L.id=="string"?L.id:null,y=null}else if(rt==="tool_input_delta"){let $=(eo=L.toolCallId)!=null?eo:R.lastId;if($){let z=W.get($);z!=null&&z.toolCall&&(z.toolCall.chunks=(jo=z.toolCall.chunks)!=null?jo:[],z.toolCall.chunks.push((rs=L.delta)!=null?rs:""),u(z))}}else{if(rt==="tool_input_complete")continue;if(rt==="turn_complete"){let $=L.stopReason,z=h!=null?h:y;if($&&z!==null){let K=L.id;(!K||((va=z.agentMetadata)==null?void 0:va.turnId)===K)&&(z.stopReason=$,u(z))}xe===L.id&&(xe=null)}else if(rt==="media_start"){let $=String(L.id);Ce.set($,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,role:typeof L.role=="string"?L.role:void 0,toolCallId:L.toolCallId,parts:[]})}else if(rt==="media_delta"){let $=Ce.get(String(L.id));$&&typeof L.delta=="string"&&$.parts.push(L.delta)}else if(rt==="media_complete"){let $=String(L.id),z=Ce.get($);Ce.delete($);let K=($n=(os=typeof L.mediaType=="string"?L.mediaType:void 0)!=null?os:z==null?void 0:z.mediaType)!=null?$n:"application/octet-stream",G=typeof L.data=="string"?L.data:void 0,De=typeof L.url=="string"?L.url:z&&z.parts.length>0?z.parts.join(""):void 0,tt=null;if(G)tt={type:"media",data:G,mediaType:K};else if(De){let kr=K.toLowerCase();tt={type:kr==="image"||kr.startsWith("image/")?"image-url":"file-url",url:De,mediaType:K}}let lt=(ko=L.toolCallId)!=null?ko:z==null?void 0:z.toolCallId,Sl=tt?[tt]:[],yn=[];for(let kr of Sl){if(!kr||typeof kr!="object")continue;let ur=kr,Xo=typeof ur.type=="string"?ur.type:void 0,Ho=typeof ur.mediaType=="string"?ur.mediaType.toLowerCase():"",sr=null,Lr="";if(Xo==="media"){let gr=typeof ur.data=="string"?ur.data:void 0;if(!gr)continue;Lr=Ho.length>0?Ho:"application/octet-stream",sr=`data:${Lr};base64,${gr}`}else if(Xo==="image-url"){let gr=typeof ur.url=="string"?ur.url:void 0;if(!gr)continue;Lr=Ho,sr=gr}else if(Xo==="file-url"){let gr=typeof ur.url=="string"?ur.url:void 0;if(!gr)continue;Lr=Ho,sr=gr}else continue;if(sr)if(Xo==="image-url"||Lr.startsWith("image/"))yn.push({type:"image",image:sr,...Lr.includes("/")?{mimeType:Lr}:{}});else if(Lr.startsWith("audio/"))yn.push({type:"audio",audio:sr,mimeType:Lr});else if(Lr.startsWith("video/"))yn.push({type:"video",video:sr,mimeType:Lr});else{let gr=Lr||"application/octet-stream";yn.push({type:"file",data:sr,mimeType:gr,filename:rv(gr)})}}if(yn.length>0){let kr=p(),ur=lt,Ho={id:`agent-media-${typeof ur=="string"&&ur.length>0?`${ur}-${kr}`:String(kr)}`,role:"assistant",content:"",contentParts:yn,createdAt:new Date().toISOString(),streaming:!1,sequence:kr,agentMetadata:{executionId:L.executionId,iteration:typeof L.iteration=="number"?L.iteration:ve}};u(Ho);let sr=h;sr&&(sr.streaming=!1,u(sr)),h=null,E.current=null}}else if(rt==="execution_complete"){let $=(gn=L.kind)!=null?gn:Ye;$==="agent"&&de&&(de.status=L.success?"complete":"error",de.completedAt=Ee(L.completedAt),de.stopReason=L.stopReason);let z=h;z&&($==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,u(z)),h=null),A=null,k="",jt=null,r({type:"status",status:"idle",terminal:!0})}else if(rt==="execution_error"){let $=typeof L.error=="string"?L.error:(nr=(it=L.error)==null?void 0:it.message)!=null?nr:"Execution error";r({type:"error",error:new Error($)})}else if(rt!=="ping"){if(rt==="approval_start"){let $=(ar=L.approvalId)!=null?ar:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(Lo=de==null?void 0:de.agentId)!=null?Lo:"virtual",executionId:(Go=(ns=L.executionId)!=null?ns:de==null?void 0:de.executionId)!=null?Go:"",toolName:(jn=L.toolName)!=null?jn:"",toolType:L.toolType,description:(q=L.description)!=null?q:`Execute ${(Po=L.toolName)!=null?Po:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};u(z)}else if(rt==="step_await"&&L.awaitReason==="approval_required"){let $=(wa=L.approvalId)!=null?wa:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(to=de==null?void 0:de.agentId)!=null?to:"virtual",executionId:(Ko=(Ro=L.executionId)!=null?Ro:de==null?void 0:de.executionId)!=null?Ko:"",toolName:(Io=L.toolName)!=null?Io:"",toolType:L.toolType,description:(Ca=L.description)!=null?Ca:`Execute ${(fo=L.toolName)!=null?fo:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};u(z)}else if(rt==="approval_complete"){let $=L.approvalId;if($){let K={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:(Xs=L.decision)!=null?Xs:"approved",agentId:(vr=de==null?void 0:de.agentId)!=null?vr:"virtual",executionId:(mo=(Tr=L.executionId)!=null?Tr:de==null?void 0:de.executionId)!=null?mo:"",toolName:(Er=L.toolName)!=null?Er:"",description:(Gn=L.description)!=null?Gn:"",resolvedAt:Date.now()}};u(K)}}else if(rt==="artifact_start"||rt==="artifact_delta"||rt==="artifact_update"||rt==="artifact_complete"){if(rt==="artifact_start"){let $=L.artifactType,z=String(L.id),K=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:z,artifactType:$,title:K,component:typeof L.component=="string"?L.component:void 0}),Te.set(z,{markdown:"",title:K}),!ge.has(z)){ge.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:K,artifactType:$,status:"streaming"}})};se.set(z,G),u(G)}}else if(rt==="artifact_delta"){let $=String(L.id),z=typeof L.delta=="string"?L.delta:String((go=L.delta)!=null?go:"");r({type:"artifact_delta",id:$,artDelta:z});let K=Te.get($);K&&(K.markdown+=z)}else if(rt==="artifact_update"){let $=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:$,component:typeof L.component=="string"?L.component:void 0})}else if(rt==="artifact_complete"){let $=String(L.id);r({type:"artifact_complete",id:$});let z=se.get($);if(z){z.streaming=!1;try{let K=JSON.parse((wr=z.rawContent)!=null?wr:"{}");if(K.props){K.props.status="complete";let G=Te.get($);G!=null&&G.markdown&&(K.props.markdown=G.markdown)}z.rawContent=JSON.stringify(K)}catch{}Te.delete($),u(z),se.delete($)}}}else if(rt==="transcript_insert"){let $=L.message;if(!$||typeof $!="object")continue;let z=String((Wo=$.id)!=null?Wo:`msg-${p()}`),K=$.role,De={id:z,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:p()};if(u(De),De.rawContent)try{let tt=JSON.parse(De.rawContent),lt=(Sa=tt==null?void 0:tt.props)==null?void 0:Sa.artifactId;typeof lt=="string"&&ge.add(lt)}catch{}h=null,E.current=null,le.delete(z),ke.delete(z)}else if(rt==="error"){if(L.recoverable===!1&&L.error!=null&&L.error!==""){let $=typeof L.error=="string"?L.error:((Kn=L.error)==null?void 0:Kn.message)!=null?String(L.error.message):"Execution error";r({type:"error",error:new Error($)});let z=h;z&&z.streaming&&(z.streaming=!1,u(z)),r({type:"status",status:"idle"})}}else if(rt==="step_error"||rt==="dispatch_error"||rt==="flow_error"){let $=null;if(L.error instanceof Error)$=L.error;else if(rt==="dispatch_error"){let z=(Aa=L.message)!=null?Aa:L.error;z!=null&&z!==""&&($=new Error(String(z)))}else{let z=L.error;typeof z=="string"&&z!==""?$=new Error(z):z!=null&&typeof z=="object"&&Reflect.has(z,"message")&&($=new Error(String((hn=z.message)!=null?hn:z)))}if($){r({type:"error",error:$});let z=h;z&&z.streaming&&(z.streaming=!1,u(z)),r({type:"status",status:"idle"})}}}}}st.length=0};;){let{done:H,value:ce}=await a.read();if(H)break;i+=s.decode(ce,{stream:!0});let Se=i.split(`
|
|
9
|
+
${e.description}`:"");return window.confirm(n)},Ky=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)}},Xy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Jy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Jo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ds(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Qy="agent_",Yy="flow_";function If(e){return e.startsWith(Qy)?{kind:"agentId",agentId:e}:e.startsWith(Yy)?{kind:"flowId",flowId:e}:null}function Bf(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=If(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=If(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 fo=po(Os(),1);var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Hn=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Wf=()=>document.createDocumentFragment(),De=(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},$n=(...e)=>e.filter(Boolean).join(" ");var ka="ask_user_question",Ea=8,kr="data-persona-ask-sheet-for",ox="Other",rx="Other\u2026",Ff="Type your own answer here",Nf="Send",ax="Next",sx="Back",ix="Submit all",lx="Skip",dx=3,Gl="data-ask-current-index",Kl="data-ask-question-count",Of="data-ask-answers",Xl="data-ask-grouped",_f="data-ask-layout",cx=e=>e.layout==="pills"?"pills":"rows",px=e=>e.getAttribute(_f)==="pills"?"pills":"rows",Df=!1,Uf=e=>e.replace(/["\\]/g,"\\$&"),jn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ka,_s=e=>e?.features?.askUserQuestion??{},Gn=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,fo.parse)(r,fo.STR|fo.OBJ|fo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},La=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ea&&!Df&&(Df=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ea}.`)),t.slice(0,Ea)},ux=e=>La(e)[0]??null,fx=(e,t)=>La(e)[t]??null,qf=(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))},Vf=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},mx=(e,t,n,o)=>{let a=y("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=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=Vf(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},gx=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},hx=(e,t,n,o)=>{let a=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");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<dx;d++)a.appendChild(gx(o));return a}if(p.forEach((d,u)=>{a.appendChild(mx(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?ox:rx;if(o==="rows"){let u=y("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=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Ff,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=Vf(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=y("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},zf=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Ff,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=y("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Nf,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},yx=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Nf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},xx=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??sx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=y("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??lx,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??ix:n.nextLabel??ax,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Qo=e=>{let t=e.getAttribute(Of);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},$f=(e,t)=>{e.setAttribute(Of,JSON.stringify(t))},xn=e=>{let t=Number(e.getAttribute(Gl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},bx=(e,t)=>{e.setAttribute(Gl,String(Math.max(0,Math.floor(t))))},Lr=e=>{let t=Number(e.getAttribute(Kl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Xl)==="true",vx=(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},Cx=(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)))},Us=(e,t)=>{let{payload:n}=Gn(t),o=La(n),r=Qo(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},jf=e=>{let t=Qo(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="")},Gf=e=>{if(!mo(e))return;let t=Qo(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}},Jl=(e,t,n)=>{let o=_s(n),r=px(e),{payload:a,complete:s}=Gn(t),l=mo(e),p=xn(e),c=Lr(e),d=l?fx(a,p):ux(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 S=e.querySelector('[data-ask-pill-list="true"]');if(S){let M=hx(d,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(zf(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!E?e.appendChild(yx(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=xx(p,c,o);k?k.replaceWith(M):e.appendChild(M)}else k&&k.remove();jf(e),Gf(e)},wx=(e,t,n)=>{let o=_s(t),r=cx(o),a=e.toolCall.id,s=La(n),l=Math.max(1,s.length),p=l>1,c=vx(e,s),d=p?Cx(e,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(kr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Kl,String(l)),u.setAttribute(Gl,String(d)),u.setAttribute(Xl,p?"true":"false"),u.setAttribute(_f,r),$f(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`),qf(u,o);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=y("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let E=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(zf(o,r)),Jl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ax=(e,t,n)=>{let{payload:o}=Gn(t),r=Math.max(1,La(o).length);r>Lr(e)&&(e.setAttribute(Kl,String(r)),r>1&&!mo(e)&&e.setAttribute(Xl,"true")),Jl(e,t,n)},Kf=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=_s(t);qf(n,o);let r=y("span","persona-ask-stub-label"),{complete:a}=Gn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Pr=(e,t,n)=>{if(!n||!jn(e)||_s(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${kr}]`).forEach(c=>{c.getAttribute(kr)!==r&&c.remove()});let s=n.querySelector(`[${kr}="${Uf(r)}"]`);if(s){Ax(s,e,t);return}let{payload:l}=Gn(e),p=wx(e,t,l);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${kr}="${Uf(t)}"]`:`[${kr}]`;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)})},Ql=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=Qo(e),o=xn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,$f(e,n),jf(e),Gf(e)},qs=(e,t,n,o)=>{let r=Lr(e),a=Math.max(0,Math.min(r-1,o));bx(e,a),Jl(e,t,n)};var En="suggest_replies";var Yl={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},Vs={name:En,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:Yl,origin:"sdk",annotations:{readOnlyHint:!0}},Zl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pa=e=>e.variant==="tool"&&e.toolCall?.name===En,ed=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},zs=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Pa(n))continue;let o=ed(n.toolCall?.args);return o.length>0?o:null}return null},Xf=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var td={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ea,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},nd={name:ka,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:td,origin:"sdk",annotations:{readOnlyHint:!0}},Rr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(nd),Xf(e)&&t.push(Vs),t};var Kn=po(Os(),1),$s=e=>e.replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=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)}},Sx=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`},Jf=e=>e.status==="complete"?Sx(e):e.status==="pending"?"Waiting":"",Mx=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 Qf=e=>e.status==="complete"?Mx(e):"Using tool...",js=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ia=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 js(t)},Gs=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return js(t)},od=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ia(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ks=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Ra(o,n.slice(a,s.index),[]),s[1]!==void 0?Ra(o,s[1],["bold"]):s[2]!==void 0?Ra(o,s[2],["italic"]):s[3]!==void 0&&Ra(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Ra(o,n.slice(a),[]),o},Ra=(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})},Tx=()=>{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
|
+
`).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()=>{}}},Ba=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xs=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Js=()=>{let e=Tx();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)}},Qs=()=>{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,Kn.parse)(n,Kn.STR|Kn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?$s(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=$s(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Yf=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?$s(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?$s(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,Kn.parse)(a,Kn.STR|Kn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Ys=()=>{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 Zf="4.9.0";var Yo=Zf;var kx="https://api.runtype.com/v1/dispatch",Zs="https://api.runtype.com";function Lx(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 rd=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 Px(e){switch(e){case"json":return Qs;case"regex-json":return Js;case"xml":return Ys;default:return Xs}}var em=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Rx(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=Ba(e);return Ba(t)!==null&&s===null?t:e}var Zo=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??kx,this.headers={"Content-Type":"application/json","X-Persona-Version":Yo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Px(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 Er(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=Bf(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$/,"")||Zs}/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":Yo},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$/,"")||Zs}/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":Yo},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(rd).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":Yo},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$/,"")||Zs}/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?Rf(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(/\/+$/,"")||Zs}/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=[...Rr(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(rd).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=[...Rr(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(rd).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=[...Rr(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=I=>{let J=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,C=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,P=I.tools?I.tools.map(B=>({...B,chunks:B.chunks?[...B.chunks]:void 0})):void 0;return{...I,reasoning:J,toolCall:C,tools:P}},g=I=>{if(I.role!=="assistant"||I.variant)return!0;let J=Array.isArray(I.contentParts)&&I.contentParts.length>0,C=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||J||C||!!I.stopReason},f=I=>{g(I)&&n({type:"message",message:u(I)})},h=null,S=null,E={current:null},k={current:null},M=null,A="",w=new Map,T=new Map,R=new Map,b=new Map,W=new Map,F={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},N=I=>{if(I==null)return null;try{return String(I)}catch{return null}},U=I=>N(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),fe=I=>N(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),pe=o,Ee=!1,Fe=()=>{if(h)return h;let I,J="",C=M;return!Ee&&pe?(I=pe,Ee=!0,J=r??""):pe&&C?I=`${pe}_${C}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:I,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},se=(I,J)=>{F.lastId=J,I&&F.byStep.set(I,J)},be=(I,J)=>{let C=I.reasoningId??I.id,P=U(I);if(C){let O=String(C);return se(P,O),O}if(P){let O=F.byStep.get(P);if(O)return F.lastId=O,O}if(F.lastId&&!J)return F.lastId;if(!J)return null;let B=`reason-${d()}`;return se(P,B),B},Z=I=>{let J=b.get(I);if(J)return J;let C={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:I,status:"streaming",chunks:[]}};return b.set(I,C),f(C),C},de=(I,J)=>{$.lastId=J,I&&$.byCall.set(I,J)},Y=new Set,ve=new Map,we=new Set,xe=new Map,He=I=>{if(!I)return!1;let J=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Oe=(I,J)=>{let C=I.toolId??I.id,P=fe(I);if(C){let O=String(C);return de(P,O),O}if(P){let O=$.byCall.get(P);if(O)return $.lastId=O,O}if($.lastId&&!J)return $.lastId;if(!J)return null;let B=`tool-${d()}`;return de(P,B),B},Xe=I=>{let J=W.get(I);if(J)return J;let C={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:I,status:"pending"}};return W.set(I,C),f(C),C},qe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let J=Number(I);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let C=Date.parse(I);if(!Number.isNaN(C))return C}return Date.now()},ke=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},Ie=new Map,it=new Map,_e=new Map,Qe=(I,J,C)=>{let P=_e.get(I);P||(P=[],_e.set(I,P));let B=0,O=P.length;for(;B<O;){let _=B+O>>>1;P[_].seq<J?B=_+1:O=_}P[B]?.seq===J?P[B]={seq:J,text:C}:P.splice(B,0,{seq:J,text:C});let X="";for(let _=0;_<P.length;_++)X+=P[_].text;return X},fn=(I,J)=>{let C=ke(J),P=it.get(I.id),B=Rx(P,C);I.rawContent=B;let O=Ie.get(I.id),X=Se=>{let dt=I.content??"";Se.trim()!==""&&(dt.trim().length===0||Se.startsWith(dt)||Se.trimStart().startsWith(dt.trim()))&&(I.content=Se)},_=()=>{if(O){let Se=O.close?.();Se instanceof Promise&&Se.catch(()=>{})}Ie.delete(I.id),it.delete(I.id),I.streaming=!1,f(I)};if(!O){X(C),_();return}let j=Ba(B);if(j!==null&&j.trim()!==""){X(j),_();return}let ae=Se=>{let dt=typeof Se=="string"?Se:Se?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let G=O.getExtractedText();return G!==null&&G.trim()!==""?G:C},nt;try{nt=O.processChunk(B)}catch{X(C),_();return}if(nt instanceof Promise){nt.then(Se=>{X(ae(Se)),_()}).catch(()=>{X(C),_()});return}X(ae(nt)),_()},Lt=null,mt=(I,J,C,P)=>{I.rawContent=J,Ie.has(I.id)||Ie.set(I.id,this.createStreamParser());let B=Ie.get(I.id),O=J.trim().startsWith("{")||J.trim().startsWith("[");if(O&&it.set(I.id,J),B.__isPlainTextParser===!0){I.content=P!==void 0?J:I.content+C,it.delete(I.id),Ie.delete(I.id),I.rawContent=void 0,f(I);return}let _=B.processChunk(J);if(_ instanceof Promise)_.then(j=>{let ae=typeof j=="string"?j:j?.text??null;ae!==null&&ae.trim()!==""?(I.content=ae,f(I)):!O&&!J.trim().startsWith("<")&&(I.content=P!==void 0?J:I.content+C,it.delete(I.id),Ie.delete(I.id),I.rawContent=void 0,f(I))}).catch(()=>{I.content=P!==void 0?J:I.content+C,it.delete(I.id),Ie.delete(I.id),I.rawContent=void 0,f(I)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(I.content=j,f(I)):!O&&!J.trim().startsWith("<")&&(I.content=P!==void 0?J:I.content+C,it.delete(I.id),Ie.delete(I.id),I.rawContent=void 0,f(I))}},Me=(I,J)=>{let C=J??I.content;if(C==null||C===""){I.streaming=!1,f(I);return}let B=it.get(I.id)??ke(C);I.rawContent=B;let O=Ie.get(I.id),X=null,_=!1;if(O&&(X=O.getExtractedText(),X===null&&(X=Ba(B)),X===null)){let j=O.processChunk(B);j instanceof Promise?(_=!0,j.then(ae=>{let nt=typeof ae=="string"?ae:ae?.text??null;nt!==null&&(I.content=nt,I.streaming=!1,Ie.delete(I.id),it.delete(I.id),f(I))}).catch(()=>{})):X=typeof j=="string"?j:j?.text??null}if(!_){X!==null&&X.trim()!==""?I.content=X:it.has(I.id)||(I.content=ke(C));let j=Ie.get(I.id);if(j){let ae=j.close?.();ae instanceof Promise&&ae.catch(()=>{}),Ie.delete(I.id)}it.delete(I.id),I.streaming=!1,f(I)}},me=(I,J,C)=>{let P=T.get(I);if(P)return P;let B={id:`nested-${J}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...C?{variant:C}:{},...C==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return T.set(I,B),f(B),B},lt=[],Le,ue=new Map,ie=0,he="agent",bt=!1,q=null,te=null,We=new Map,Ae=this.config.iterationDisplay??"separate";for(Le=()=>{for(let I=0;I<lt.length;I++){let J=lt[I].payloadType,C=lt[I].payload;if(!bt&&he!=="flow"&&typeof C.stepType=="string"&&(he="flow"),J==="reasoning_start"){let P=typeof C.id=="string"?C.id:null,B=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(P&&B){w.set(P,B),me(P,B,"reasoning");continue}let O=be(C,!0)??`reason-${d()}`,X=Z(O);X.reasoning=X.reasoning??{id:O,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??qe(C.startedAt??C.timestamp),X.reasoning.completedAt=void 0,X.reasoning.durationMs=void 0,(C.scope==="loop"||C.scope==="turn")&&(X.reasoning.scope=C.scope),X.streaming=!0,X.reasoning.status="streaming",f(X)}else if(J==="reasoning_delta"){let P=typeof C.id=="string"?C.id:null;if(P&&w.has(P)&&T.has(P)){let _=T.get(P),j=C.reasoningText??C.text??C.delta??"";j&&C.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let B=be(C,!1)??be(C,!0)??`reason-${d()}`,O=Z(B);O.reasoning=O.reasoning??{id:B,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??qe(C.startedAt??C.timestamp);let X=C.reasoningText??C.text??C.delta??"";if(X&&C.hidden!==!0){let _=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(_!==void 0){let j=Qe(B,_,String(X));O.reasoning.chunks=[j]}else O.reasoning.chunks.push(String(X))}if(O.reasoning.status=C.done?"complete":"streaming",C.done){O.reasoning.completedAt=qe(C.completedAt??C.timestamp);let _=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-_)}O.streaming=O.reasoning.status!=="complete",f(O)}else if(J==="reasoning_complete"){let P=typeof C.id=="string"?C.id:null;if(P&&w.has(P)&&T.has(P)){let j=T.get(P);if(j.reasoning){let ae=typeof C.text=="string"?C.text:"";ae&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(ae),j.reasoning.status="complete",j.streaming=!1,f(j)}w.delete(P),T.delete(P);continue}let B=be(C,!1)??be(C,!0)??`reason-${d()}`,O=typeof C.text=="string"?C.text:"";!b.get(B)&&(O||C.scope==="loop")&&Z(B);let X=b.get(B);if(X?.reasoning){(C.scope==="loop"||C.scope==="turn")&&(X.reasoning.scope=C.scope),O&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(O),X.reasoning.status="complete",X.reasoning.completedAt=qe(C.completedAt??C.timestamp);let j=X.reasoning.startedAt??Date.now();X.reasoning.durationMs=Math.max(0,(X.reasoning.completedAt??Date.now())-j),X.streaming=!1,f(X)}let _=U(C);_&&F.byStep.delete(_)}else if(J==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof C.iteration=="number"&&(ie=C.iteration);let P=(typeof C.toolCallId=="string"?C.toolCallId:void 0)??Oe(C,!0)??`tool-${d()}`,B=C.toolName??C.name;if(He(B)){Y.add(P);continue}de(fe(C),P);let O=Xe(P),X=O.toolCall??{id:P,status:"pending"};X.name=B??X.name,X.status="running",C.parameters!==void 0?X.args=C.parameters:C.args!==void 0&&(X.args=C.args),X.startedAt=X.startedAt??qe(C.startedAt??C.timestamp),X.completedAt=void 0,X.durationMs=void 0,O.toolCall=X,O.streaming=!0,C.executionId&&(O.agentMetadata={executionId:C.executionId,iteration:C.iteration}),f(O)}else if(J==="tool_output_delta"){let P=Oe(C,!1)??Oe(C,!0)??`tool-${d()}`;if(Y.has(P))continue;let B=Xe(P),O=B.toolCall??{id:P,status:"running"};O.startedAt=O.startedAt??qe(C.startedAt??C.timestamp);let X=C.text??C.delta??C.message??"";X&&(O.chunks=O.chunks??[],O.chunks.push(String(X))),O.status="running",B.toolCall=O,B.streaming=!0;let _=C.agentContext;(_||C.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:_?.executionId??C.executionId,iteration:_?.iteration??C.iteration}),f(B)}else if(J==="tool_complete"){let P=Oe(C,!1)??Oe(C,!0)??`tool-${d()}`;if(Y.has(P)){Y.delete(P);continue}let B=Xe(P),O=B.toolCall??{id:P,status:"running"};O.status="complete",C.result!==void 0&&(O.result=C.result),typeof C.duration=="number"&&(O.duration=C.duration),O.completedAt=qe(C.completedAt??C.timestamp);let X=C.duration??C.executionTime;if(typeof X=="number")O.durationMs=X;else{let ae=O.startedAt??Date.now();O.durationMs=Math.max(0,(O.completedAt??Date.now())-ae)}B.toolCall=O,B.streaming=!1;let _=C.agentContext;(_||C.executionId)&&(B.agentMetadata=B.agentMetadata??{executionId:_?.executionId??C.executionId,iteration:_?.iteration??C.iteration}),f(B);let j=fe(C);j&&$.byCall.delete(j)}else if(J==="await"&&C.toolName){let P=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,B=P??C.toolId??`local-${d()}`,O=Xe(B),X=C.toolName,_=C.origin==="webmcp"&&!uo(X)?`webmcp:${X}`:X,j=uo(_),ae=O.toolCall??{id:B,status:"pending"};ae.name=_,ae.args=C.parameters,ae.status=j?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??qe(C.startedAt??C.timestamp??C.awaitedAt),j?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,O.toolCall=ae,O.streaming=!1,O.agentMetadata={...O.agentMetadata,executionId:C.executionId??O.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(O)}else if(J==="text_start"){let P=typeof C.id=="string"?C.id:null,B=typeof C.parentToolCallId=="string"&&C.parentToolCallId?C.parentToolCallId:null;if(P&&B){w.set(P,B);continue}let O=h;O&&(he==="flow"?(Me(O),Lt=O):(O.streaming=!1,f(O)),h=null),M=typeof C.id=="string"?C.id:M,A=""}else if(J==="text_delta"){let P=typeof C.id=="string"?C.id:null,B=P?w.get(P):void 0;if(P&&B){let X=typeof C.delta=="string"?C.delta:"",_=(R.get(P)??"")+X;if(R.set(P,_),_.trim()==="")continue;let j=me(P,B);j.agentMetadata={...j.agentMetadata,executionId:C.executionId,parentToolId:B},mt(j,_,X,void 0);continue}if(M=typeof C.id=="string"?C.id:M,he==="flow"){let X=typeof C.delta=="string"?C.delta:"";if(A+=X,A.trim()==="")continue;let _=Fe();_.agentMetadata={executionId:C.executionId,iteration:C.iteration},mt(_,A,X,void 0),S=_;continue}let O=Fe();O.content+=C.delta??"",O.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:q??void 0,agentName:te?.agentName},S=O,f(O)}else if(J==="text_complete"){let P=typeof C.id=="string"?C.id:null;if(P&&w.has(P)){let O=T.get(P);O&&Me(O),w.delete(P),R.delete(P),T.delete(P);continue}let B=h;B&&(he==="flow"?(Me(B),Lt=B):((B.content??"")===""&&typeof C.text=="string"&&(B.content=C.text),B.streaming=!1,f(B)),h=null),M=null,A=""}else if(J==="step_complete"){let P=C.stepType,B=C.executionType;if(P==="tool"||B==="context")continue;if(C.success===!1){let O=C.error,X=typeof O=="string"&&O!==""?O:O!=null&&typeof O=="object"&&Reflect.has(O,"message")?String(O.message??"Step failed"):"Step failed";n({type:"error",error:new Error(X)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let O=Lt;Lt=null;let X=C.stopReason,_=C.result?.response;if(O)X&&(O.stopReason=X),_!=null?fn(O,_):O.streaming!==!1&&(Ie.delete(O.id),it.delete(O.id),O.streaming=!1,f(O));else{let j=_!=null&&_!=="";if(j||X){let ae=Fe();X&&(ae.stopReason=X),j?Me(ae,_):(ae.streaming=!1,f(ae))}}continue}}else if(J==="execution_start")he=C.kind==="flow"?"flow":"agent",bt=!0,he==="agent"&&(te={executionId:C.executionId,agentId:C.agentId??"virtual",agentName:C.agentName??"",status:"running",currentIteration:0,maxTurns:C.maxTurns??1,startedAt:qe(C.startedAt)});else if(J==="turn_start"){let P=typeof C.iteration=="number"?C.iteration:ie;if(P!==ie){if(te&&(te.currentIteration=P),Ae==="separate"&&P>1){let B=h;B&&(B.streaming=!1,f(B),We.set(P-1,B),h=null)}ie=P}q=typeof C.id=="string"?C.id:null,S=null}else if(J==="tool_input_delta"){let P=C.toolCallId??$.lastId;if(P){let B=W.get(P);B?.toolCall&&(B.toolCall.chunks=B.toolCall.chunks??[],B.toolCall.chunks.push(C.delta??""),f(B))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let P=C.stopReason,B=h??S;if(P&&B!==null){let O=C.id;(!O||B.agentMetadata?.turnId===O)&&(B.stopReason=P,f(B))}q===C.id&&(q=null)}else if(J==="media_start"){let P=String(C.id);ue.set(P,{mediaType:typeof C.mediaType=="string"?C.mediaType:void 0,role:typeof C.role=="string"?C.role:void 0,toolCallId:C.toolCallId,parts:[]})}else if(J==="media_delta"){let P=ue.get(String(C.id));P&&typeof C.delta=="string"&&P.parts.push(C.delta)}else if(J==="media_complete"){let P=String(C.id),B=ue.get(P);ue.delete(P);let O=(typeof C.mediaType=="string"?C.mediaType:void 0)??B?.mediaType??"application/octet-stream",X=typeof C.data=="string"?C.data:void 0,_=typeof C.url=="string"?C.url:B&&B.parts.length>0?B.parts.join(""):void 0,j=null;if(X)j={type:"media",data:X,mediaType:O};else if(_){let dt=O.toLowerCase();j={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:_,mediaType:O}}let ae=C.toolCallId??B?.toolCallId,nt=j?[j]:[],Se=[];for(let dt of nt){if(!dt||typeof dt!="object")continue;let G=dt,Ve=typeof G.type=="string"?G.type:void 0,Pe=typeof G.mediaType=="string"?G.mediaType.toLowerCase():"",Re=null,Te="";if(Ve==="media"){let Ye=typeof G.data=="string"?G.data:void 0;if(!Ye)continue;Te=Pe.length>0?Pe:"application/octet-stream",Re=`data:${Te};base64,${Ye}`}else if(Ve==="image-url"){let Ye=typeof G.url=="string"?G.url:void 0;if(!Ye)continue;Te=Pe,Re=Ye}else if(Ve==="file-url"){let Ye=typeof G.url=="string"?G.url:void 0;if(!Ye)continue;Te=Pe,Re=Ye}else continue;if(Re)if(Ve==="image-url"||Te.startsWith("image/"))Se.push({type:"image",image:Re,...Te.includes("/")?{mimeType:Te}:{}});else if(Te.startsWith("audio/"))Se.push({type:"audio",audio:Re,mimeType:Te});else if(Te.startsWith("video/"))Se.push({type:"video",video:Re,mimeType:Te});else{let Ye=Te||"application/octet-stream";Se.push({type:"file",data:Re,mimeType:Ye,filename:Lx(Ye)})}}if(Se.length>0){let dt=d(),G=ae,Pe={id:`agent-media-${typeof G=="string"&&G.length>0?`${G}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Se,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:C.executionId,iteration:typeof C.iteration=="number"?C.iteration:ie}};f(Pe);let Re=h;Re&&(Re.streaming=!1,f(Re)),h=null,E.current=null}}else if(J==="execution_complete"){let P=C.kind??he;P==="agent"&&te&&(te.status=C.success?"complete":"error",te.completedAt=qe(C.completedAt),te.stopReason=C.stopReason);let B=h;B&&(P==="flow"&&B.streaming!==!1?Me(B):(B.streaming=!1,f(B)),h=null),M=null,A="",Lt=null,n({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let P=typeof C.error=="string"?C.error:C.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(J!=="ping"){if(J==="approval_start"){let P=C.approvalId??`approval-${d()}`,B={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:P,status:"pending",agentId:te?.agentId??"virtual",executionId:C.executionId??te?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(B)}else if(J==="step_await"&&C.awaitReason==="approval_required"){let P=C.approvalId??`approval-${d()}`,B={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:P,status:"pending",agentId:te?.agentId??"virtual",executionId:C.executionId??te?.executionId??"",toolName:C.toolName??"",toolType:C.toolType,description:C.description??`Execute ${C.toolName??"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(B)}else if(J==="approval_complete"){let P=C.approvalId;if(P){let O={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:P,status:C.decision??"approved",agentId:te?.agentId??"virtual",executionId:C.executionId??te?.executionId??"",toolName:C.toolName??"",description:C.description??"",resolvedAt:Date.now()}};f(O)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let P=C.artifactType,B=String(C.id),O=typeof C.title=="string"?C.title:void 0,X=C.file,_;X&&typeof X=="object"&&!Array.isArray(X)&&typeof X.path=="string"&&typeof X.mimeType=="string"&&(_={path:X.path,mimeType:X.mimeType,...typeof X.language=="string"?{language:X.language}:{}}),n({type:"artifact_start",id:B,artifactType:P,title:O,component:typeof C.component=="string"?C.component:void 0,..._?{file:_}:{}});let j=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?{...C.props}:void 0;if(xe.set(B,{markdown:"",title:O,file:_,...j?{props:j}:{}}),!we.has(B)){we.add(B);let ae=Jo(this.config.features?.artifacts,P),nt=typeof C.component=="string"?C.component:void 0,Se={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ds(ae,{artifactId:B,title:O,artifactType:P,status:"streaming",..._?{file:_}:{},...nt?{component:nt}:{}})};ve.set(B,Se),f(Se)}}else if(J==="artifact_delta"){let P=String(C.id),B=typeof C.delta=="string"?C.delta:String(C.delta??"");n({type:"artifact_delta",id:P,artDelta:B});let O=xe.get(P);O&&(O.markdown+=B)}else if(J==="artifact_update"){let P=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:P,component:typeof C.component=="string"?C.component:void 0});let B=xe.get(String(C.id));B&&(B.props={...B.props??{},...P})}else if(J==="artifact_complete"){let P=String(C.id);n({type:"artifact_complete",id:P});let B=ve.get(P);if(B){B.streaming=!1;try{let O=JSON.parse(B.rawContent??"{}");if(O.props){O.props.status="complete";let X=xe.get(P);X?.markdown&&(O.props.markdown=X.markdown),X?.file&&(O.props.file=X.file),O.component==="PersonaArtifactInline"&&X?.props&&Object.keys(X.props).length>0&&(O.props.componentProps=X.props)}B.rawContent=JSON.stringify(O)}catch{}xe.delete(P),f(B),ve.delete(P)}}}else if(J==="transcript_insert"){let P=C.message;if(!P||typeof P!="object")continue;let B=String(P.id??`msg-${d()}`),O=P.role,_={id:B,role:O==="user"?"user":O==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:d()};if(f(_),_.rawContent)try{let ae=JSON.parse(_.rawContent)?.props?.artifactId;typeof ae=="string"&&we.add(ae)}catch{}h=null,E.current=null,Ie.delete(B),it.delete(B)}else if(J==="error"){if(C.recoverable===!1&&C.error!=null&&C.error!==""){let P=typeof C.error=="string"?C.error:C.error?.message!=null?String(C.error.message):"Execution error";n({type:"error",error:new Error(P)});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let P=null;if(C.error instanceof Error)P=C.error;else if(J==="dispatch_error"){let B=C.message??C.error;B!=null&&B!==""&&(P=new Error(String(B)))}else{let B=C.error;typeof B=="string"&&B!==""?P=new Error(B):B!=null&&typeof B=="object"&&Reflect.has(B,"message")&&(P=new Error(String(B.message??B)))}if(P){n({type:"error",error:P});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:I,value:J}=await a.read();if(I)break;l+=s.decode(J,{stream:!0});let C=l.split(`
|
|
13
13
|
|
|
14
|
-
`);
|
|
15
|
-
`),et="message",Qe="",gt=null;for(let ae of Ie)ae.startsWith("event:")?et=ae.replace("event:","").trim():ae.startsWith("data:")?Qe+=ae.replace("data:","").trim():ae.startsWith("id:")&&(gt=ae.slice(3).trim());let pe=()=>{gt!==null&>!==""&&r({type:"cursor",id:gt})};if(!Qe){pe();continue}let N;try{N=JSON.parse(Qe)}catch(ae){r({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let ye=et!=="message"?et:(Co=N.type)!=null?Co:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,ye,N),this.parseSSEEvent){E.current=h;let ae=await this.handleCustomSSEEvent(N,r,E,u,p,T);if(E.current&&E.current!==h&&(h=E.current),ae){pe();continue}}st.push({payloadType:ye,payload:N}),je(),pe()}}je()}};function Ah(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function _a(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function In(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Si="[Image]";function Mh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Th(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Eh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function kh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Es(e){return{type:"text",text:e}}function Lh(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Ph(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Rh(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Ih=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],av=["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"],on=[...Ih,...av];function sv(e){return Ih.includes(e)||e.startsWith("image/")}function Ai(e){return sv(e.type)}async function Wh(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;Ai(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Hh(e,t=on,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function iv(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Bh(e,t){let r=iv(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]||r||"FILE"}var Mi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.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 r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);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 r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);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 r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Dh=16e3,lv=24e3,dv=4096,cv=1380533830;function pv(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===cv?new Uint8Array(e,44):new Uint8Array(e)}function uv(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ks=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Dh,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(y=>y.stop());return}this.mediaStream=d;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:Dh});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let g=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new Mi(lv);if(n!==this.callGeneration){g.destroy(),d.getTracks().forEach(y=>y.stop()),m.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${uv(o)}/ws/agents/${encodeURIComponent(t)}/voice`,h=new WebSocket(u,["runtype.bearer",r]);h.binaryType="arraybuffer",this.ws=h,h.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,d,h,n))},h.onmessage=y=>this.handleMessage(y,n),h.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},h.onclose=y=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(y.code!==1e3){let E=y.code?` (code ${y.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}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,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(dv,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let p=0;p<c.length;p++){let m=Math.max(-1,Math.min(1,c[p]));d[p]=m<0?m*32768:m*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!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,r){if(r!==this.callGeneration||!this.playback)return;let o=pv(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(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var da=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("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(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}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 Wn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ks(e.runtype);case"browser":if(!da.isSupported())throw new Error("Browser speech recognition not supported");return new da(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ti(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Wn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Wn({type:"runtype",runtype:e.runtype});if(da.isSupported())return Wn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ls(e){try{return Ti(e),!0}catch{return!1}}function Ua(e){var r;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 o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var Hn=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Ua(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,p;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ca=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!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,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{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(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function od(e){if(!e)return"";let t=fv(e);return Fh(t!==null?t:e)}function fv(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[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 Fh(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
14
|
+
`);l=C.pop()??"";for(let P of C){let B=P.split(`
|
|
15
|
+
`),O="message",X="",_=null;for(let Se of B)Se.startsWith("event:")?O=Se.replace("event:","").trim():Se.startsWith("data:")?X+=Se.replace("data:","").trim():Se.startsWith("id:")&&(_=Se.slice(3).trim());let j=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!X){j();continue}let ae;try{ae=JSON.parse(X)}catch(Se){n({type:"error",error:Se instanceof Error?Se:new Error("Failed to parse chat stream payload")});continue}let nt=O!=="message"?O:ae.type??"message";if(this.onSSEEvent?.(nt,ae),this.parseSSEEvent){E.current=h;let Se=await this.handleCustomSSEEvent(ae,n,E,f,d,k);if(E.current&&E.current!==h&&(h=E.current),Se){j();continue}}lt.push({payloadType:nt,payload:ae}),Le(),j()}}Le()}};function tm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ir(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ei="[Image]";function nm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function om(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ti(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 bo(e){return{type:"text",text:e}}function am(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function sm(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 im(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 lm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ix=["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"],Xn=[...lm,...Ix];function Bx(e){return lm.includes(e)||e.startsWith("image/")}function ni(e){return Bx(e.type)}async function dm(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 cm(e,t=Xn,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 Hx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function pm(e,t){let n=Hx(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 oi=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 um=16e3,Wx=24e3,Dx=4096,Fx=1380533830;function Nx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Fx?new Uint8Array(e,44):new Uint8Array(e)}function Ox(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 Ha=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:um,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:um});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new oi(Wx);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=`${Ox(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(Dx,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=Nx(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 er=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 vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ha(e.runtype);case"browser":if(!er.isSupported())throw new Error("Browser speech recognition not supported");return new er(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 ri(e){if(e?.type==="custom"&&e.custom)return vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return vo({type:"runtype",runtype:e.runtype});if(er.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wa(e){try{return ri(e),!0}catch{return!1}}function Br(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 Co=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):Br(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 tr=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 ad(e){if(!e)return"";let t=_x(e);return fm(t!==null?t:e)}function _x(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 fm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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
|
|
17
|
+
`),t.trim()}var sd=null,mm=e=>{sd=e},id=()=>sd?sd():import("./runtype-tts-entry");var Vx=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function zx(e,t){return Vx.some(n=>e[n]!==t[n])}function ld(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: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]}),Uh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,qh=e=>Tn(e)||e===bo,qa=class{constructor(t={},r){this.config=t;this.callbacks=r;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 ca(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,p,m;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let g=t.message.toolCall,u=!!(g!=null&&g.name)&&(Tn(g.name)||g.name===bo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&u&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.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:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(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),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new la(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(d=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId)!=null?d:this.config.agentId;!r||!o||!this.config.clientToken||ad().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ls((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=Hn.isSupported()?new Hn({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId)!=null?c:this.config.agentId,m=this.config.clientToken,g=t.browserFallback!==!1;if(d&&p&&m)return ad().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:h})=>{let y=new u({host:d,agentId:p,clientToken:m,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new h(y,r,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):y});if(g&&r)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Wn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=p.id}if(d){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:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=p.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),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(){var r,o,n,a,s,i,c,d,p,m,g,u;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(d=(c=t.runtype)==null?void 0:c.host)!=null?d:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(m=t.runtype)==null?void 0:m.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!xv(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new la(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:p,rawContent:m}=t,u={id:s!=null?s:r==="user"?_a():r==="assistant"?In():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(u),u}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 r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:p,streaming:m=!1,voiceProcessing:g,rawContent:u}=o,y={id:c!=null?c:n==="user"?_a():n==="assistant"?In():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};r.push(y)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,p,m,g,u;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let n=_a(),a=In();this.activeAssistantMessageId=null;let s={id:n,role:"user",content:o||Si,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(h){if(this.status==="resuming"||this.reconnecting)return;let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let E=sd(h,this.config.errorMessage);if(E){let T={id:a,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(h instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,h):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(h))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort(),this.teardownReconnect();let t=In();this.activeAssistantMessageId=null,this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let p=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!p){let m=sd(d,this.config.errorMessage);if(m){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var a,s,i;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(a=this.abortController)==null||a.abort(),r!=null&&r.preserveAssistantId&&r.assistantMessageId&&(this.activeAssistantMessageId=r.assistantMessageId);let o=r!=null&&r.preserveAssistantId?r.assistantMessageId:void 0,n=!1;for(let c of this.messages)c.streaming&&c.id!==o&&(c.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId,r==null?void 0:r.seedContent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(s=this.callbacks).onError)==null||i.call(s,c instanceof Error?c:new Error(String(c)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,m,g,u,h;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(y=>y.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let y;if(d?y=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):y=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),y){let E=null;if(y instanceof Response){if(!y.ok){let T=await y.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${y.status}`)}E=y.body}else y instanceof ReadableStream&&(E=y);E?await this.connectStream(E,{allowReentry:!0}):(r==="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(y){let E=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(h=(u=this.callbacks).onError)==null||h.call(u,y instanceof Error?y:new Error(String(y)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,m,g,u,h,y,E,T,A,k,w,C;let o=this.messages.find(S=>S.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(m=t.agentMetadata)==null?void 0:m.executionId,a=(g=t.toolCall)==null?void 0:g.name;if(!n||!a){(h=(u=this.callbacks).onError)==null||h.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let S=(y=t.toolCall)==null?void 0:y.args,M=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(M.length===1){let W=typeof((E=M[0])==null?void 0:E.question)=="string"?M[0].question:"";W&&(s={[W]:r})}}this.markAskUserQuestionResolved(t,s),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let S=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=s!=null?s:{};d.forEach((M,W)=>{let I=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!I)return;let R=S[I],D=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:D||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(n,{[a]:r});if(!S.ok){let M=await S.json().catch(()=>null);throw new Error((k=M==null?void 0:M.error)!=null?k:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let M=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(C=(w=this.callbacks).onError)==null||C.call(w,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==bo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=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:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,p,m;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async g=>{var C,S,M,W,I,R,D;let u=(C=g.toolCall)==null?void 0:C.name,h=(S=g.toolCall)==null?void 0:S.id;if(!u||!h)return null;let y=`${t}:${h}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(y),o.push(y);let E=this.markWebMcpToolRunning(g),T=(W=(M=g.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?W:u;if(u===bo)return{dedupeKey:y,resumeKey:T,output:Jl(),toolMessage:g,startedAt:E,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let k=this.client.executeWebMcpToolCall(u,(I=g.toolCall)==null?void 0:I.args,A.signal),w;if(!k)w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{w=await k}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(D=(R=this.callbacks).onError)==null||D.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,Ps(Q?"Aborted by cancel()":Uh(O)),E),this.webMcpInflightKeys.delete(y),null}return A.signal.aborted?(this.markWebMcpToolComplete(g,Ps("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(y),null):{dedupeKey:y,resumeKey:T,output:w,toolMessage:g,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=s.filter(h=>h!==null),i.length===0)return;let g={};for(let h of i)g[h.resumeKey]=h.output;let u=await this.client.resumeFlow(t,g,{signal:a.signal});if(!u.ok){let h=await u.json().catch(()=>null);throw new Error((c=h==null?void 0:h.error)!=null?c:`Resume failed: ${u.status}`)}for(let h of i)this.webMcpResolvedKeys.add(h.dedupeKey),this.markWebMcpToolComplete(h.toolMessage,h.output,h.startedAt,h.completedAt,((d=h.toolMessage.toolCall)==null?void 0:d.name)===bo?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,g instanceof Error?g:new Error(String(g)));else for(let h of i)this.markWebMcpToolComplete(h.toolMessage,Ps("Aborted by cancel()"),h.startedAt)}finally{for(let g of o)this.webMcpInflightKeys.delete(g);for(let g of n)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var h,y,E,T,A,k,w,C,S,M,W,I;let r=(h=t.agentMetadata)==null?void 0:h.executionId,o=(y=t.toolCall)==null?void 0:y.name,n=(E=t.toolCall)==null?void 0:E.id;if(!r){(A=(T=this.callbacks).onError)==null||A.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let R=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(D){(w=(k=this.callbacks).onError)==null||w.call(k,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(R)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===bo,p=(C=t.toolCall)==null?void 0:C.args,m=d?null:this.client.executeWebMcpToolCall(o,p,c),g="execute",u=s;try{let R;if(d?R=Jl():m?R=await m:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Ps("Aborted by cancel()"),s);return}let D=(M=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?M:o;g="resume",await this.resumeWithToolOutput(r,D,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,R,s,u,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(R){let D=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(g==="execute"||D||c.aborted)&&this.markWebMcpToolComplete(t,Ps(D||c.aborted?"Aborted by cancel()":Uh(R)),s),D||(I=(W=this.callbacks).onError)==null||I.call(W,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0: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){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}trackCursor(t){var n,a;let r=(n=this.agentExecution)==null?void 0:n.executionId;if(!r||!this.activeAssistantMessageId||((a=this.agentExecution)==null?void 0:a.status)!=="running")return;let o=this.resumable===null;this.resumable={executionId:r,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var r,o,n;return((r=t.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&((o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((n=t.approval)==null?void 0:n.status)==="pending"})}beginReconnect(){var t,r;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(r=(t=this.callbacks).onReconnect)==null||r.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(o=>{this.reconnecting&&this.resumable&&o.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(_h(),Oh)).then(({createReconnectController:t})=>{let r=t(this.buildReconnectHost());return this.reconnectController=r,r})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:r=>t.setStatus(r),setStreaming:r=>t.setStreaming(r),setReconnecting:r=>{t.reconnecting=r},setAbortController:r=>{t.abortController=r},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(r,o,n)=>t.connectStream(r,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:r=>t.appendMessage(r),nextSequence:()=>t.nextSequence(),emitReconnect:r=>{var o,n;return(n=(o=t.callbacks).onReconnect)==null?void 0:n.call(o,r)},buildErrorContent:r=>sd(new Error(r),t.config.errorMessage),onError:r=>{var o,n;return(n=(o=t.callbacks).onError)==null?void 0:n.call(o,r)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let r=this.reopenTrailingAssistant();r||(r=In(),this.appendMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=r,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:r,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(r.role==="assistant"&&!r.variant)return r.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),r.id;if(r.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var r,o;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((o=(r=this.config).onExecutionState)==null||o.call(r,null))}notifyExecutionState(t){let r=this.config.onExecutionState;if(r){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),r(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var o,n;this.executionStateTimer=null,(n=(o=this.config).onExecutionState)==null||n.call(o,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 r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let 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 n=od(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ua(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=od(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,m,g,u,h,y,E,T,A,k,w,C,S,M,W;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=n.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(g=s.agentMetadata)!=null?g:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let I=n.approval,R=r.approval;s.approval={...I,...R,executionId:R.executionId||I.executionId,toolName:R.toolName||I.toolName,description:R.description||I.description,toolType:(u=R.toolType)!=null?u:I.toolType,reason:(h=R.reason)!=null?h:I.reason,parameters:(y=R.parameters)!=null?y:I.parameters}}let i=(E=r.toolCall)==null?void 0:E.name,c=(T=r.agentMetadata)==null?void 0:T.executionId,d=(A=r.toolCall)==null?void 0:A.id;if(i&&qh(i)&&c&&d&&((k=r.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let I=`${c}:${d}`,R=this.webMcpInflightKeys.has(I),D=this.webMcpResolvedKeys.has(I),O=(w=n.toolCall)==null?void 0:w.name,Q=((C=n.agentMetadata)==null?void 0:C.executionId)===c&&((S=n.toolCall)==null?void 0:S.id)===d&&O!==void 0&&qh(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(R||D||Q)&&(s.agentMetadata={...(W=s.agentMetadata)!=null?W:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.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((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var id=[["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 ld=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var dd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var cd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var pd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var ud=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var fd=[["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 md=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var gd=[["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 hd=[["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 xd=[["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 yd=[["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 bd=[["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 vd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var wd=[["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 Cd=[["path",{d:"M20 6 9 17l-5-5"}]];var Sd=[["path",{d:"m6 9 6 6 6-6"}]];var Ad=[["path",{d:"m15 18-6-6 6-6"}]];var Md=[["path",{d:"m9 18 6-6-6-6"}]];var Td=[["path",{d:"m18 15-6-6-6 6"}]];var Ei=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var ki=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Ed=[["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 kd=[["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 Ld=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Pd=[["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 Rd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Id=[["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 Wd=[["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 Li=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Pi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Hd=[["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 Bd=[["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 Dd=[["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 Fd=[["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 Nd=[["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 Od=[["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 _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"}]];var Ud=[["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 qd=[["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 Vd=[["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 zd=[["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 $d=[["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 Ri=[["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 jd=[["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 Gd=[["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 Kd=[["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 Xd=[["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 Qd=[["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 Jd=[["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 Ii=[["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 Yd=[["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 Zd=[["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 ec=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var tc=[["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 rc=[["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 Wi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var oc=[["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 nc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ac=[["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 sc=[["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 ic=[["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 lc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var dc=[["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 cc=[["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 pc=[["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 uc=[["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 fc=[["path",{d:"M5 12h14"}]];var mc=[["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 gc=[["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 hc=[["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 xc=[["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 yc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var bc=[["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 vc=[["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 wc=[["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 Cc=[["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 Sc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ac=[["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 Mc=[["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 Tc=[["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 Ec=[["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 kc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Lc=[["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 Pc=[["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 Rc=[["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 Ic=[["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 Wc=[["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 Hi=[["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 Hc=[["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 Bc=[["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 Dc=[["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 Fc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Bi=[["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 Nc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Oc=[["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 _c=[["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 Uc=[["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 qc=[["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 Vc=[["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 zc=[["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 $c=[["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 jc=[["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 Gc=[["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 Di=[["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 Kc=[["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 Xc=[["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 Qc=[["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 Jc=[["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 Yc=[["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 Zc=[["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 ep=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var tp=[["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 yv={activity:id,"arrow-down":ld,"arrow-up":ud,"arrow-up-right":pd,bot:xd,"chevron-down":Sd,"chevron-up":Td,"chevron-right":Md,"chevron-left":Ad,check:Cd,clipboard:kd,"clipboard-copy":Ed,copy:Pd,file:_d,"file-code":Fd,"file-spreadsheet":Nd,"file-text":Od,"image-plus":Yd,loader:oc,"loader-circle":Wi,mic:pc,paperclip:xc,"refresh-cw":Mc,search:kc,send:Lc,"shield-alert":Ic,"shield-check":Wc,"shield-x":Hi,square:Nc,"thumbs-down":Vc,"thumbs-up":zc,upload:Xc,"volume-2":Jc,x:ep,user:Qc,mail:ac,phone:wc,calendar:vd,clock:Ld,building:yd,"map-pin":sc,lock:nc,key:tc,"credit-card":Rd,"at-sign":fd,hash:Kd,globe:Gd,link:rc,"circle-check":Ei,"circle-x":ki,"triangle-alert":Di,info:ec,ban:md,shield:Hc,"arrow-left":dd,"arrow-right":cd,"external-link":Bd,ellipsis:Pi,"ellipsis-vertical":Li,menu:lc,house:Ii,plus:Sc,minus:fc,pencil:bc,trash:Gc,"trash-2":jc,save:Ec,download:Wd,share:Rc,funnel:Ri,settings:Pc,"rotate-cw":Tc,maximize:ic,minimize:uc,"shopping-cart":Dc,"shopping-bag":Bc,package:hc,truck:Kc,tag:qc,gift:jd,receipt:Ac,wallet:Zc,store:_c,"dollar-sign":Id,percent:vc,play:Cc,pause:yc,"volume-x":Yc,camera:wd,image:Zd,film:qd,headphones:Xd,"message-circle":dc,"message-square":cc,bell:gd,heart:Qd,star:Oc,eye:Dd,"eye-off":Hd,bookmark:hd,"calendar-days":bd,history:Jd,timer:$c,folder:$d,"folder-open":zd,files:Ud,sparkles:Bi,zap:tp,sun:Uc,moon:gc,flag:Vd,monitor:mc,smartphone:Fc},he=(e,t=24,r="currentColor",o=2)=>{let n=yv[e];return n?bv(n,t,r,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 bv(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),n.appendChild(c)}),n}var Fi={allowedTypes:on,maxFileSize:10*1024*1024,maxFiles:4};function vv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function wv(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 pa=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Fi.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Fi.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Fi.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:Fi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let p=Hh(d,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,m);continue}try{let m=await Wh(d),g=Ai(d)?URL.createObjectURL(d):null,u={id:vv(),file:d,previewUrl:g,contentPart:m};this.attachments.push(u),this.renderPreview(u)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=Ai(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",r&&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 i=wv(t.file.type),c=he(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=v("span");d.textContent=Bh(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 n=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=he("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Vh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rs(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];Vh(a)&&Vh(n)?r[o]=Rs(a,n):r[o]=n}return r}var Gr="min(440px, calc(100vw - 24px))",Ni="440px",Cv={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:Gr,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)"},Wt={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:Cv,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function zh(e,t){if(!(!e&&!t))return e?t?Rs(e,t):e:t}function Oi(e){var t,r,o,n,a,s,i,c,d,p,m,g,u,h,y,E,T,A,k,w,C;return e?{...Wt,...e,theme:zh(Wt.theme,e.theme),darkTheme:zh(Wt.darkTheme,e.darkTheme),launcher:{...Wt.launcher,...e.launcher,dock:{...(t=Wt.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Wt.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Wt.copy,...e.copy},sendButton:{...Wt.sendButton,...e.sendButton},statusIndicator:{...Wt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Wt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le;let S=(oe=Wt.features)==null?void 0:oe.artifacts,M=(se=e.features)==null?void 0:se.artifacts,W=(ge=Wt.features)==null?void 0:ge.scrollToBottom,I=(Te=e.features)==null?void 0:Te.scrollToBottom,R=(qe=Wt.features)==null?void 0:qe.scrollBehavior,D=(j=e.features)==null?void 0:j.scrollBehavior,O=(ee=Wt.features)==null?void 0:ee.streamAnimation,Q=(Ee=e.features)==null?void 0:Ee.streamAnimation,me=(te=Wt.features)==null?void 0:te.askUserQuestion,ue=(le=e.features)==null?void 0:le.askUserQuestion,Z=S===void 0&&M===void 0?void 0:{...S,...M,layout:{...S==null?void 0:S.layout,...M==null?void 0:M.layout}},Le=W===void 0&&I===void 0?void 0:{...W,...I},He=R===void 0&&D===void 0?void 0:{...R,...D},ie=O===void 0&&Q===void 0?void 0:{...O,...Q},Me=me===void 0&&ue===void 0?void 0:{...me,...ue,styles:{...me==null?void 0:me.styles,...ue==null?void 0:ue.styles}};return{...Wt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...He!==void 0?{scrollBehavior:He}:{},...Z!==void 0?{artifacts:Z}:{},...ie!==void 0?{streamAnimation:ie}:{},...Me!==void 0?{askUserQuestion:Me}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Wt.suggestionChips,suggestionChipsConfig:{...Wt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Wt.layout,...e.layout,header:{...(s=Wt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Wt.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(m=(p=Wt.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(u=(g=e.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(y=(h=Wt.layout)==null?void 0:h.messages)==null?void 0:y.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(A=Wt.layout)==null?void 0:A.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Wt.markdown,...e.markdown,options:{...(w=Wt.markdown)==null?void 0:w.options,...(C=e.markdown)==null?void 0:C.options}},messageActions:{...Wt.messageActions,...e.messageActions}}:Wt}var rp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},op={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},np={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Gr,maxWidth:Ni,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Va(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Va(e,o):o}function _i(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Va(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function ap(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function $h(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=$h(a,n):r[o]=n}return r}function Sv(e,t){return t?$h(e,t):e}function za(e,t={}){var n,a,s,i,c,d,p,m,g,u,h,y,E;let r={palette:rp,semantic:op,components:np},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(g=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...r.semantic.colors.feedback,...(h=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:h.feedback}},spacing:{...r.semantic.spacing,...(y=e==null?void 0:e.semantic)==null?void 0:y.spacing},typography:{...r.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Sv(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=ap(o);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)o=T.transform(o);return o}function Ui(e){var y,E,T,A,k,w,C,S,M,W,I,R,D,O,Q,me,ue,Z,Le,He,ie,Me,oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe,X,st,je,Ce,ve,Ye,Vt,xe,de,Ar,Ct,br,wo,Co,Ve,H,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,er,So,Uo,io,lo,sn,zt,co,qo,Fr,Wr,Nr,po,Ao,ln,Qr,dn,St,Mo,To,Vo,uo,ht,Un,Eo,qn,Hr,ba,cn,zo,pn,un,Vn,zn,fn,vt,Or,_r,Mr,At,Jr,Yr,Ur,mn;let t=_i(e),r={};for(let[we,$o]of Object.entries(t)){let Zr=we.replace(/\./g,"-");r[`--persona-${Zr}`]=$o.value}r["--persona-primary"]=(y=r["--persona-semantic-colors-primary"])!=null?y:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(E=r["--persona-semantic-colors-secondary"])!=null?E:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(T=r["--persona-semantic-colors-accent"])!=null?T:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(k=r["--persona-semantic-colors-background"])!=null?k:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(w=r["--persona-semantic-colors-container"])!=null?w:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(C=r["--persona-semantic-colors-text"])!=null?C:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(S=r["--persona-semantic-colors-text-muted"])!=null?S:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(I=r["--persona-semantic-colors-divider"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(R=r["--persona-components-voice-recording-indicator"])!=null?R:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(D=r["--persona-components-voice-recording-background"])!=null?D:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ue=r["--persona-components-approval-requested-border"])!=null?ue:r["--persona-border"],r["--persona-approval-text"]=(Z=r["--persona-components-approval-requested-text"])!=null?Z:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Le=r["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(He=r["--persona-components-approval-approve-background"])!=null?He:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(ie=r["--persona-components-approval-deny-background"])!=null?ie:r["--persona-container"],r["--persona-attachment-image-bg"]=(Me=r["--persona-components-attachment-image-background"])!=null?Me:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(oe=r["--persona-components-attachment-image-border"])!=null?oe:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(se=r["--persona-semantic-typography-fontFamily"])!=null?se:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ge=r["--persona-semantic-typography-fontSize"])!=null?ge:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Te=r["--persona-semantic-typography-fontWeight"])!=null?Te:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(qe=r["--persona-semantic-typography-lineHeight"])!=null?qe:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(j=r["--persona-palette-radius-sm"])!=null?j:"0.125rem",r["--persona-radius-md"]=(ee=r["--persona-palette-radius-md"])!=null?ee:"0.375rem",r["--persona-radius-lg"]=(Ee=r["--persona-palette-radius-lg"])!=null?Ee:"0.5rem",r["--persona-radius-xl"]=(te=r["--persona-palette-radius-xl"])!=null?te:"0.75rem",r["--persona-radius-full"]=(le=r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-radius"]=(nt=(ke=r["--persona-components-launcher-borderRadius"])!=null?ke:r["--persona-palette-radius-full"])!=null?nt:"9999px",r["--persona-launcher-bg"]=(yt=r["--persona-components-launcher-background"])!=null?yt:r["--persona-primary"],r["--persona-launcher-fg"]=(Kt=r["--persona-components-launcher-foreground"])!=null?Kt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(jt=r["--persona-components-launcher-border"])!=null?jt:r["--persona-border"],r["--persona-button-primary-bg"]=(ct=r["--persona-components-button-primary-background"])!=null?ct:r["--persona-primary"],r["--persona-button-primary-fg"]=(fe=r["--persona-components-button-primary-foreground"])!=null?fe:r["--persona-text-inverse"],r["--persona-button-radius"]=(st=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?st:"9999px",r["--persona-panel-radius"]=(Ce=(je=r["--persona-components-panel-borderRadius"])!=null?je:r["--persona-radius-xl"])!=null?Ce:"0.75rem",r["--persona-panel-border"]=(ve=r["--persona-components-panel-border"])!=null?ve:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Vt=(Ye=r["--persona-components-panel-shadow"])!=null?Ye:r["--persona-palette-shadows-xl"])!=null?Vt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(xe=r["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Ar=(de=r["--persona-components-input-borderRadius"])!=null?de:r["--persona-radius-lg"])!=null?Ar:"0.5rem",r["--persona-message-user-radius"]=(br=(Ct=r["--persona-components-message-user-borderRadius"])!=null?Ct:r["--persona-radius-lg"])!=null?br:"0.5rem",r["--persona-message-assistant-radius"]=(Co=(wo=r["--persona-components-message-assistant-borderRadius"])!=null?wo:r["--persona-radius-lg"])!=null?Co:"0.5rem",r["--persona-header-bg"]=(Ve=r["--persona-components-header-background"])!=null?Ve:r["--persona-surface"],r["--persona-header-border"]=(H=r["--persona-components-header-border"])!=null?H:r["--persona-divider"],r["--persona-header-icon-bg"]=(ce=r["--persona-components-header-iconBackground"])!=null?ce:r["--persona-primary"],r["--persona-header-icon-fg"]=(Se=r["--persona-components-header-iconForeground"])!=null?Se:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ae=r["--persona-components-header-titleForeground"])!=null?Ae:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ie=r["--persona-components-header-subtitleForeground"])!=null?Ie:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(et=r["--persona-components-header-actionIconForeground"])!=null?et:r["--persona-muted"];let o=(Qe=e.components)==null?void 0:Qe.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(gt=e.components)==null?void 0:gt.introCard;r["--persona-intro-card-bg"]=(pe=r["--persona-components-introCard-background"])!=null?pe:r["--persona-surface"],r["--persona-intro-card-radius"]=(N=r["--persona-components-introCard-borderRadius"])!=null?N:"1rem",r["--persona-intro-card-padding"]=(ye=r["--persona-components-introCard-padding"])!=null?ye:"1.5rem",r["--persona-intro-card-shadow"]=(mt=(ae=n==null?void 0:n.shadow)!=null?ae:r["--persona-components-introCard-shadow"])!=null?mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ke=r["--persona-components-input-background"])!=null?Ke:r["--persona-surface"],r["--persona-input-placeholder"]=(Lt=r["--persona-components-input-placeholder"])!=null?Lt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Et=r["--persona-components-message-user-background"])!=null?Et:r["--persona-accent"],r["--persona-message-user-text"]=(bt=r["--persona-components-message-user-text"])!=null?bt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(It=r["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Qt=r["--persona-components-message-assistant-background"])!=null?Qt:r["--persona-surface"],r["--persona-message-assistant-text"]=(Ft=r["--persona-components-message-assistant-text"])!=null?Ft:r["--persona-text"],r["--persona-message-assistant-border"]=(er=r["--persona-components-message-assistant-border"])!=null?er:r["--persona-border"],r["--persona-message-assistant-shadow"]=(So=r["--persona-components-message-assistant-shadow"])!=null?So:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(io=(Uo=r["--persona-components-scrollToBottom-background"])!=null?Uo:r["--persona-button-primary-bg"])!=null?io:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(sn=(lo=r["--persona-components-scrollToBottom-foreground"])!=null?lo:r["--persona-button-primary-fg"])!=null?sn:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(zt=r["--persona-components-scrollToBottom-border"])!=null?zt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(co=r["--persona-components-scrollToBottom-size"])!=null?co:"40px",r["--persona-scroll-to-bottom-radius"]=(Wr=(Fr=(qo=r["--persona-components-scrollToBottom-borderRadius"])!=null?qo:r["--persona-button-radius"])!=null?Fr:r["--persona-radius-full"])!=null?Wr:"9999px",r["--persona-scroll-to-bottom-shadow"]=(po=(Nr=r["--persona-components-scrollToBottom-shadow"])!=null?Nr:r["--persona-palette-shadows-sm"])!=null?po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Ao=r["--persona-components-scrollToBottom-padding"])!=null?Ao:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(ln=r["--persona-components-scrollToBottom-gap"])!=null?ln:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(dn=(Qr=r["--persona-components-scrollToBottom-fontSize"])!=null?Qr:r["--persona-palette-typography-fontSize-sm"])!=null?dn:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(St=r["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",r["--persona-tool-bubble-shadow"]=(Mo=r["--persona-components-toolBubble-shadow"])!=null?Mo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(To=r["--persona-components-reasoningBubble-shadow"])!=null?To:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Vo=r["--persona-components-composer-shadow"])!=null?Vo:"none",r["--persona-md-inline-code-bg"]=(uo=r["--persona-components-markdown-inlineCode-background"])!=null?uo:r["--persona-container"],r["--persona-md-inline-code-color"]=(ht=r["--persona-components-markdown-inlineCode-foreground"])!=null?ht:r["--persona-text"],r["--persona-md-link-color"]=(Eo=(Un=r["--persona-components-markdown-link-foreground"])!=null?Un:r["--persona-accent"])!=null?Eo:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(qn=r["--persona-components-markdown-codeBlock-background"])!=null?qn:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Hr=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Hr:r["--persona-border"],r["--persona-md-code-block-text-color"]=(ba=r["--persona-components-markdown-codeBlock-textColor"])!=null?ba:"inherit",r["--persona-md-table-header-bg"]=(cn=r["--persona-components-markdown-table-headerBackground"])!=null?cn:r["--persona-container"],r["--persona-md-table-border-color"]=(zo=r["--persona-components-markdown-table-borderColor"])!=null?zo:r["--persona-border"],r["--persona-md-hr-color"]=(pn=r["--persona-components-markdown-hr-color"])!=null?pn:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(un=r["--persona-components-markdown-blockquote-borderColor"])!=null?un:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Vn=r["--persona-components-markdown-blockquote-background"])!=null?Vn:"transparent",r["--persona-md-blockquote-text-color"]=(zn=r["--persona-components-markdown-blockquote-textColor"])!=null?zn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(fn=r["--persona-components-collapsibleWidget-container"])!=null?fn:r["--persona-surface"],r["--cw-surface"]=(vt=r["--persona-components-collapsibleWidget-surface"])!=null?vt:r["--persona-surface"],r["--cw-border"]=(Or=r["--persona-components-collapsibleWidget-border"])!=null?Or:r["--persona-border"],r["--persona-message-border"]=(_r=r["--persona-components-message-border"])!=null?_r:r["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(r["--persona-icon-btn-bg"]=m.background),m.border&&(r["--persona-icon-btn-border"]=m.border),m.color&&(r["--persona-icon-btn-color"]=m.color),m.padding&&(r["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(r["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(r["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(r["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(r["--persona-icon-btn-active-border"]=m.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(r["--persona-label-btn-bg"]=g.background),g.border&&(r["--persona-label-btn-border"]=g.border),g.color&&(r["--persona-label-btn-color"]=g.color),g.padding&&(r["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(r["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(r["--persona-label-btn-gap"]=g.gap));let u=p==null?void 0:p.toggleGroup;u&&(u.gap&&(r["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(r["--persona-toggle-group-radius"]=u.borderRadius));let h=p==null?void 0:p.artifact;if(h!=null&&h.toolbar){let we=h.toolbar;we.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,r["--persona-dropdown-bg"]=(Mr=r["--persona-dropdown-bg"])!=null?Mr:we.copyMenuBackground),we.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,r["--persona-dropdown-border"]=(At=r["--persona-dropdown-border"])!=null?At:we.copyMenuBorder),we.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,r["--persona-dropdown-shadow"]=(Jr=r["--persona-dropdown-shadow"])!=null?Jr:we.copyMenuShadow),we.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Yr=r["--persona-dropdown-radius"])!=null?Yr:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ur=r["--persona-dropdown-item-hover-bg"])!=null?Ur:we.copyMenuItemHoverBackground),we.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(h!=null&&h.tab){let we=h.tab;we.background&&(r["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(r["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(r["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(r["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(r["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(r["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(r["--persona-artifact-tab-list-padding"]=we.listPadding)}if(h!=null&&h.pane){let we=h.pane;if(we.toolbarBackground){let $o=(mn=Va(e,we.toolbarBackground))!=null?mn:we.toolbarBackground;r["--persona-artifact-toolbar-bg"]=$o}}return r}var jh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Av={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"}}},Gh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Is=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Mv=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Is()},sp=e=>Mv(e),Tv=e=>za(e),Ev=e=>{var r;let t=za(void 0,{validate:!1});return za({...e,palette:{...t.palette,colors:{...Av.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},$a=e=>{let t=sp(e),r=Gh(e==null?void 0:e.theme),o=Gh(e==null?void 0:e.darkTheme);return t==="dark"?Ev(Rs(r!=null?r:{},o!=null?o:{})):Tv(r)},kv=e=>Ui(e),Bn=(e,t)=>{let r=$a(t),o=kv(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},qi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Is())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Is());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var Kh=(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 r(g,u,h={}){g=p(g);let y=m(u),E=d(g,y,h),T=n(E,()=>i(E,g,y,A=>A.morphStyle==="innerHTML"?(a(A,g,y),Array.from(g.childNodes)):o(A,g,y)));return E.pantry.remove(),T}function o(g,u,h){let y=m(u);return a(g,y,h,u,u.nextSibling),Array.from(y.childNodes)}function n(g,u){var k;if(!g.config.restoreFocus)return u();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return u();let{id:y,selectionStart:E,selectionEnd:T}=h,A=u();return y&&y!==((k=document.activeElement)==null?void 0:k.getAttribute("id"))&&(h=g.target.querySelector(`[id="${y}"]`),h==null||h.focus()),h&&!h.selectionEnd&&T&&h.setSelectionRange(E,T),A}let a=(function(){function g(w,C,S,M=null,W=null){C instanceof HTMLTemplateElement&&S instanceof HTMLTemplateElement&&(C=C.content,S=S.content),M||(M=C.firstChild);for(let I of S.childNodes){if(M&&M!=W){let D=h(w,I,M,W);if(D){D!==M&&E(w,M,D),s(D,I,w),M=D.nextSibling;continue}}if(I instanceof Element){let D=I.getAttribute("id");if(w.persistentIds.has(D)){let O=T(C,D,M,w);s(O,I,w),M=O.nextSibling;continue}}let R=u(C,I,M,w);R&&(M=R.nextSibling)}for(;M&&M!=W;){let I=M;M=M.nextSibling,y(w,I)}}function u(w,C,S,M){if(M.callbacks.beforeNodeAdded(C)===!1)return null;if(M.idMap.has(C)){let W=document.createElement(C.tagName);return w.insertBefore(W,S),s(W,C,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(C,!0);return w.insertBefore(W,S),M.callbacks.afterNodeAdded(W),W}}let h=(function(){function w(M,W,I,R){let D=null,O=W.nextSibling,Q=0,me=I;for(;me&&me!=R;){if(S(me,W)){if(C(M,me,W))return me;D===null&&(M.idMap.has(me)||(D=me))}if(D===null&&O&&S(me,O)&&(Q++,O=O.nextSibling,Q>=2&&(D=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return D||null}function C(M,W,I){let R=M.idMap.get(W),D=M.idMap.get(I);if(!D||!R)return!1;for(let O of R)if(D.has(O))return!0;return!1}function S(M,W){var D,O,Q;let I=M,R=W;return I.nodeType===R.nodeType&&I.tagName===R.tagName&&(!((D=I.getAttribute)!=null&&D.call(I,"id"))||((O=I.getAttribute)==null?void 0:O.call(I,"id"))===((Q=R.getAttribute)==null?void 0:Q.call(R,"id")))}return w})();function y(w,C){var S;if(w.idMap.has(C))k(w.pantry,C,null);else{if(w.callbacks.beforeNodeRemoved(C)===!1)return;(S=C.parentNode)==null||S.removeChild(C),w.callbacks.afterNodeRemoved(C)}}function E(w,C,S){let M=C;for(;M&&M!==S;){let W=M;M=M.nextSibling,y(w,W)}return M}function T(w,C,S,M){var I,R;let W=((R=(I=M.target).getAttribute)==null?void 0:R.call(I,"id"))===C&&M.target||M.target.querySelector(`[id="${C}"]`)||M.pantry.querySelector(`[id="${C}"]`);return A(W,M),k(w,W,S),W}function A(w,C){let S=w.getAttribute("id");for(;w=w.parentNode;){let M=C.idMap.get(w);M&&(M.delete(S),M.size||C.idMap.delete(w))}}function k(w,C,S){if(w.moveBefore)try{w.moveBefore(C,S)}catch{w.insertBefore(C,S)}else w.insertBefore(C,S)}return g})(),s=(function(){function g(A,k,w){return w.ignoreActive&&A===document.activeElement?null:(w.callbacks.beforeNodeMorphed(A,k)===!1||(A instanceof HTMLHeadElement&&w.head.ignore||(A instanceof HTMLHeadElement&&w.head.style!=="morph"?c(A,k,w):(u(A,k,w),T(A,w)||a(w,A,k))),w.callbacks.afterNodeMorphed(A,k)),A)}function u(A,k,w){let C=k.nodeType;if(C===1){let S=A,M=k,W=S.attributes,I=M.attributes;for(let R of I)E(R.name,S,"update",w)||S.getAttribute(R.name)!==R.value&&S.setAttribute(R.name,R.value);for(let R=W.length-1;0<=R;R--){let D=W[R];if(D&&!M.hasAttribute(D.name)){if(E(D.name,S,"remove",w))continue;S.removeAttribute(D.name)}}T(S,w)||h(S,M,w)}(C===8||C===3)&&A.nodeValue!==k.nodeValue&&(A.nodeValue=k.nodeValue)}function h(A,k,w){if(A instanceof HTMLInputElement&&k instanceof HTMLInputElement&&k.type!=="file"){let C=k.value,S=A.value;y(A,k,"checked",w),y(A,k,"disabled",w),k.hasAttribute("value")?S!==C&&(E("value",A,"update",w)||(A.setAttribute("value",C),A.value=C)):E("value",A,"remove",w)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&k instanceof HTMLOptionElement)y(A,k,"selected",w);else if(A instanceof HTMLTextAreaElement&&k instanceof HTMLTextAreaElement){let C=k.value,S=A.value;if(E("value",A,"update",w))return;C!==S&&(A.value=C),A.firstChild&&A.firstChild.nodeValue!==C&&(A.firstChild.nodeValue=C)}}function y(A,k,w,C){let S=k[w],M=A[w];if(S!==M){let W=E(w,A,"update",C);W||(A[w]=k[w]),S?W||A.setAttribute(w,""):E(w,A,"remove",C)||A.removeAttribute(w)}}function E(A,k,w,C){return A==="value"&&C.ignoreActiveValue&&k===document.activeElement?!0:C.callbacks.beforeAttributeUpdated(A,k,w)===!1}function T(A,k){return!!k.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function i(g,u,h,y){if(g.head.block){let E=u.querySelector("head"),T=h.querySelector("head");if(E&&T){let A=c(E,T,g);return Promise.all(A).then(()=>{let k=Object.assign(g,{head:{block:!1,ignore:!0}});return y(k)})}}return y(g)}function c(g,u,h){let y=[],E=[],T=[],A=[],k=new Map;for(let C of u.children)k.set(C.outerHTML,C);for(let C of g.children){let S=k.has(C.outerHTML),M=h.head.shouldReAppend(C),W=h.head.shouldPreserve(C);S||W?M?E.push(C):(k.delete(C.outerHTML),T.push(C)):h.head.style==="append"?M&&(E.push(C),A.push(C)):h.head.shouldRemove(C)!==!1&&E.push(C)}A.push(...k.values());let w=[];for(let C of A){let S=document.createRange().createContextualFragment(C.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(S)!==!1){if("href"in S&&S.href||"src"in S&&S.src){let M,W=new Promise(function(I){M=I});S.addEventListener("load",function(){M()}),w.push(W)}g.appendChild(S),h.callbacks.afterNodeAdded(S),y.push(S)}}for(let C of E)h.callbacks.beforeNodeRemoved(C)!==!1&&(g.removeChild(C),h.callbacks.afterNodeRemoved(C));return h.head.afterHeadMorphed(g,{added:y,kept:T,removed:E}),w}let d=(function(){function g(w,C,S){let{persistentIds:M,idMap:W}=A(w,C),I=u(S),R=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(R))throw`Do not understand how to morph style ${R}`;return{target:w,newContent:C,config:I,morphStyle:R,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:W,persistentIds:M,pantry:h(),activeElementAndParents:y(w),callbacks:I.callbacks,head:I.head}}function u(w){let C=Object.assign({},t);return Object.assign(C,w),C.callbacks=Object.assign({},t.callbacks,w.callbacks),C.head=Object.assign({},t.head,w.head),C}function h(){let w=document.createElement("div");return w.hidden=!0,document.body.insertAdjacentElement("afterend",w),w}function y(w){let C=[],S=document.activeElement;if((S==null?void 0:S.tagName)!=="BODY"&&w.contains(S))for(;S&&(C.push(S),S!==w);)S=S.parentElement;return C}function E(w){var S;let C=Array.from(w.querySelectorAll("[id]"));return(S=w.getAttribute)!=null&&S.call(w,"id")&&C.push(w),C}function T(w,C,S,M){for(let W of M){let I=W.getAttribute("id");if(C.has(I)){let R=W;for(;R;){let D=w.get(R);if(D==null&&(D=new Set,w.set(R,D)),D.add(I),R===S)break;R=R.parentElement}}}}function A(w,C){let S=E(w),M=E(C),W=k(S,M),I=new Map;T(I,W,w,S);let R=C.__idiomorphRoot||C;return T(I,W,R,M),{persistentIds:W,idMap:I}}function k(w,C){let S=new Set,M=new Map;for(let{id:I,tagName:R}of w)M.has(I)?S.add(I):M.set(I,R);let W=new Set;for(let{id:I,tagName:R}of C)W.has(I)?S.add(I):M.get(I)===R&&W.add(I);for(let I of S)W.delete(I);return W}return g})(),{normalizeElement:p,normalizeParent:m}=(function(){let g=new WeakSet;function u(T){return T instanceof Document?T.documentElement:T}function h(T){if(T==null)return document.createElement("div");if(typeof T=="string")return h(E(T));if(g.has(T))return T;if(T instanceof Node){if(T.parentNode)return new y(T);{let A=document.createElement("div");return A.append(T),A}}else{let A=document.createElement("div");for(let k of[...T])A.append(k);return A}}class y{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],k=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;k&&k!=this.nextSibling;)A.push(k),k=k.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((k,w)=>{if(w instanceof Element){w.matches(A)&&k.push(w);let C=w.querySelectorAll(A);for(let S=0;S<C.length;S++)k.push(C[S])}return k},[])}insertBefore(A,k){return this.realParentNode.insertBefore(A,k)}moveBefore(A,k){return this.realParentNode.moveBefore(A,k)}get __idiomorphRoot(){return this.originalNode}}function E(T){let A=new DOMParser,k=T.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(k.match(/<\/html>/)||k.match(/<\/head>/)||k.match(/<\/body>/)){let w=A.parseFromString(T,"text/html");if(k.match(/<\/html>/))return g.add(w),w;{let C=w.firstChild;return C&&g.add(C),C}}else{let C=A.parseFromString("<body><template>"+T+"</template></body>","text/html").body.querySelector("template").content;return g.add(C),C}}return{normalizeElement:u,normalizeParent:h}})();return{morph:r,defaults:t}})();var Vi=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Kh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===n.getAttribute("data-tool-elapsed")?!1:void 0;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var Xh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var zi={index:-1,draft:""};function Qh(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...zi}}}function Jh(e,t){var r,o,n,a,s,i,c,d,p,m,g,u,h,y,E,T,A,k,w,C,S,M,W,I,R,D,O,Q,me,ue,Z,Le,He,ie,Me,oe,se,ge;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(d=e.llmContent)==null?void 0:d.length)!=null?p:0,(g=(m=e.approval)==null?void 0:m.status)!=null?g:"",(h=(u=e.toolCall)==null?void 0:u.status)!=null?h:"",(E=(y=e.toolCall)==null?void 0:y.name)!=null?E:"",(k=(A=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:A.length)!=null?k:0,(M=(S=(C=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:C[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(I=e.toolCall)!=null&&I.args?JSON.stringify(e.toolCall.args).length:0,(O=(D=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:D.length)!=null?O:0,(Z=(ue=(me=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?Z:0,(Me=(ie=(He=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:He[e.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?Me:"",(se=(oe=e.contentParts)==null?void 0:oe.length)!=null?se:0,(ge=e.stopReason)!=null?ge:"",t].join("\0")}function Yh(){return new Map}function Zh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function ex(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function tx(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function $i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Dn(e,t){return Oo(e)-e.scrollTop<=t}function ji(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Gi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function rx(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ox(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function nx(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var rr={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Sr=1e5,Fn=Sr+1;var Ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lv=["pre","code","a","script","style"],Ki=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ws.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ws.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ws.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ws.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ws.buffer}},sx=[{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"}],Hs=new Map;for(let e of sx)Hs.set(e.name,e);var ua=e=>{Hs.set(e.name,e)},dp=e=>{sx.some(t=>t.name===e)||Hs.delete(e)},cp=()=>Array.from(Hs.keys()),ja=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Hs.get(e))!=null?o:null},Xi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.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(`
|
|
20
|
-
`);return a<0?"":e.slice(0,a)}return e},Pv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},Rv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},ip=/\s/,Iv=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Wv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(ip.test(a[i])){let d=i;for(;d<a.length&&ip.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=i;for(;p<a.length&&!ip.test(a[p]);)d.appendChild(Pv(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(d),i=p}n.replaceChild(s,e)},Hv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(Rv(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Bs=(e,t,r,o)=>{var m,g;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((m=o==null?void 0:o.skipTags)!=null?m:Lv).map(u=>u.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Iv(c,a)||i.push(c),c=s.nextNode();let d={value:(g=o==null?void 0:o.startIndex)!=null?g:0},p=t==="char"?Wv:Hv;for(let u of i)p(u,r,d);return n.innerHTML},Qi=(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},Ds=(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 r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},ax=new WeakMap,Bv=(e,t)=>{var a;if(!e.styles)return;let r=ax.get(t);if(r||(r=new Set,ax.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},lp=new WeakMap,Dv=(e,t)=>{if(!e.onAttach)return;let r=lp.get(t);if(r||(r=new Map,lp.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},ix=e=>{let t=lp.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Ji=(e,t)=>{Bv(e,t),Dv(e,t)};function pp(e,t=Sr){let r=e.style.position,o=e.style.zIndex,n=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=r),e.style.zIndex=o,e.style.isolation=n}}var Fs=0,Nn=null;function up(e=document){var r;if(Fs++,Fs===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Nn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Fs=Math.max(0,Fs-1),Fs===0&&Nn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Nn.originalOverflow,n.style.position=Nn.originalPosition,n.style.top=Nn.originalTop,n.style.width=Nn.originalWidth,a.scrollTo(0,Nn.scrollY),Nn=null}}}var Ns={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},or=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},On=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Kr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Ns.side,width:(n=t==null?void 0:t.width)!=null?n:Ns.width,animate:(a=t==null?void 0:t.animate)!=null?a:Ns.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Ns.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Ns.maxHeight}};var vo={"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={})=>{var E,T,A,k,w,C;let{showClose:r=!0,wrapperClassName:o=Fv,buttonSize:n,iconSize:a="28px"}=t,s=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=n!=null?n:s.closeButtonSize)!=null?T:"32px",c=v("div",o),d=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(k=s.closeButtonShowTooltip)!=null?k:!0,m=(w=s.closeButtonIconName)!=null?w:"x",g=(C=s.closeButtonIconText)!=null?C:"\xD7",u=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Tt("button",{className:bs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!u&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Ir.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:u?`${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}}),y=he(m,a,"currentColor",1);if(y?(y.style.display="block",h.appendChild(y)):h.textContent=g,c.appendChild(h),p&&d){let S=null,M=()=>{if(S)return;let I=h.ownerDocument,R=I.body;if(!R)return;S=No(I,"div","persona-clear-chat-tooltip"),S.textContent=d;let D=No(I,"div");D.className="persona-clear-chat-tooltip-arrow",S.appendChild(D);let O=h.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(Fn),S.style.left=`${O.left+O.width/2}px`,S.style.top=`${O.top-8}px`,S.style.transform="translate(-50%, -100%)",R.appendChild(S)},W=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",W),h.addEventListener("focus",M),h.addEventListener("blur",W),c._cleanupTooltip=()=>{W(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",W),h.removeEventListener("focus",M),h.removeEventListener("blur",W)}}return{button:h,wrapper:c}},Nv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Zi=(e,t={})=>{var S,M,W,I,R,D,O,Q,me,ue,Z,Le,He;let{wrapperClassName:r=Nv,buttonSize:o,iconSize:n="20px"}=t,s=(M=((S=e==null?void 0:e.launcher)!=null?S:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(I=s.iconName)!=null?I:"refresh-cw",d=(R=s.iconColor)!=null?R:"",p=(D=s.backgroundColor)!=null?D:"",m=(O=s.borderWidth)!=null?O:"",g=(Q=s.borderColor)!=null?Q:"",u=(me=s.borderRadius)!=null?me:"",h=(ue=s.paddingX)!=null?ue:"",y=(Z=s.paddingY)!=null?Z:"",E=(Le=s.tooltipText)!=null?Le:"Clear chat",T=(He=s.showTooltip)!=null?He:!0,A=v("div",r),k=!!(m||g),w=Tt("button",{className:bs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!u&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:d||Ir.actionIconColor,backgroundColor:p||void 0,border:k?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:u||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:y||void 0,paddingBottom:y||void 0}}),C=he(c,n,"currentColor",1);if(C&&(C.style.display="block",w.appendChild(C)),A.appendChild(w),T&&E){let ie=null,Me=()=>{if(ie)return;let se=w.ownerDocument,ge=se.body;if(!ge)return;ie=No(se,"div","persona-clear-chat-tooltip"),ie.textContent=E;let Te=No(se,"div");Te.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Te);let qe=w.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(Fn),ie.style.left=`${qe.left+qe.width/2}px`,ie.style.top=`${qe.top-8}px`,ie.style.transform="translate(-50%, -100%)",ge.appendChild(ie)},oe=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};A.addEventListener("mouseenter",Me),A.addEventListener("mouseleave",oe),w.addEventListener("focus",Me),w.addEventListener("blur",oe),A._cleanupTooltip=()=>{oe(),A.removeEventListener("mouseenter",Me),A.removeEventListener("mouseleave",oe),w.removeEventListener("focus",Me),w.removeEventListener("blur",oe)}}return{button:w,wrapper:A}};var Ir={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))"},nn=e=>{var C,S,M,W,I,R,D,O,Q,me,ue,Z,Le,He,ie,Me;let{config:t,showClose:r=!0}=e,o=Tt("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)))"}}),n=(C=t==null?void 0:t.launcher)!=null?C:{},a=(S=n.headerIconSize)!=null?S:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,d=Tt("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(!i)if(c){let oe=parseFloat(a)||24,se=he(c,oe*.6,"currentColor",1);se?d.replaceChildren(se):d.textContent=(R=(I=t==null?void 0:t.launcher)==null?void 0:I.agentIconText)!=null?R:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let oe=v("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=a,oe.style.width=a,d.replaceChildren(oe)}else d.textContent=(Q=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Q:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Tt("span",{className:"persona-text-base persona-font-semibold",text:(ue=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ue:"Chat Assistant",style:{color:Ir.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(Le=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Ir.subtitleColor}});p.append(m,g),i?o.append(p):o.append(d,p);let u=(He=n.clearChat)!=null?He:{},h=(ie=u.enabled)!=null?ie:!0,y=(Me=u.placement)!=null?Me:"inline",E=null,T=null;if(h){let se=Zi(t,{wrapperClassName:y==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=se.button,T=se.wrapper,y==="top-right"&&(T.style.right="48px"),y==="inline"&&o.appendChild(T)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&y==="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:k,wrapper:w}=Yi(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(w),{header:o,iconHolder:d,headerTitle:m,headerSubtitle:g,closeButton:k,closeButtonWrapper:w,clearChatButton:E,clearChatButtonWrapper:T}},fa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function _n(e){let{items:t,onSelect:r,anchor:o,position:n="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(Fn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let u of t){if(u.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",u.id),u.destructive&&h.setAttribute("data-destructive",""),u.icon){let E=he(u.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let y=document.createElement("span");y.textContent=u.label,h.appendChild(y),h.addEventListener("click",E=>{E.stopPropagation(),p(),r(u.id)}),s.appendChild(h)}let i=null;function c(){if(!a)return;let u=o.getBoundingClientRect();s.style.top=`${u.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-u.right}px`,s.style.left="auto"):(s.style.left=`${u.left}px`,s.style.right="auto")}function d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=h=>{!s.contains(h.target)&&!o.contains(h.target)&&p()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function m(){s.classList.contains("persona-hidden")?d():p()}function g(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:p,toggle:m,destroy:g}}function pr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=v("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=he(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[p,m]of Object.entries(i))c.setAttribute(p,m);return c}function Os(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let p=v("button",d);if(p.type="button",p.setAttribute("aria-label",r),t){let g=he(t,a!=null?a:14,"currentColor",2);g&&p.appendChild(g)}let m=v("span");if(m.textContent=r,p.appendChild(m),i&&p.addEventListener("click",i),c)for(let[g,u]of Object.entries(c))p.setAttribute(g,u);return p}function lx(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=v("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let m;p.icon?m=pr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(m=v("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),m.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:m}),a.appendChild(m)}function d(p){s=p,c()}return{element:a,setSelected:d}}function el(e){var u,h;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=v("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=v("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let m=he(r,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",d.appendChild(m)),c&&(d.style.borderRadius=(u=c.borderRadius)!=null?u:"10px",d.style.padding=(h=c.padding)!=null?h:"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",()=>{var y,E;d.style.backgroundColor=(y=c.background)!=null?y:"",d.style.borderColor=(E=c.border)!=null?E:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let g=_n({items:o,onSelect:y=>{d.setAttribute("aria-expanded","false"),n(y)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",y=>{y.stopPropagation();let E=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),d.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d.click())}),{element:d,setLabel:y=>{p.textContent=y,d.setAttribute("aria-label",y)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let y=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",y?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var fp=e=>{var o;let t=nn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Ov(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=he(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=v("div","persona-relative");c.appendChild(i);let d=_n({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",p=>{p.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var mp=e=>{var A,k,w,C,S,M,W,I,R;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,d,p;if(c)d=el({label:(k=s.title)!=null?k:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=Ir.titleColor,p=(w=d.querySelector(".persona-combo-btn-label"))!=null?w:d;else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Ir.titleColor,p.textContent=(C=s.title)!=null?C:"Chat Assistant",d.appendChild(p),Ov(d,n==null?void 0:n.trailingActions,(S=n==null?void 0:n.onAction)!=null?S:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let O=n.onTitleClick;d.addEventListener("click",Q=>{Q.target.closest("button")||O()}),d.addEventListener("keydown",Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),O())})}let D=n==null?void 0:n.titleRowHover;D&&(d.style.borderRadius=(M=D.borderRadius)!=null?M:"10px",d.style.padding=(W=D.padding)!=null?W:"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",()=>{var O,Q;d.style.backgroundColor=(O=D.background)!=null?O:"",d.style.borderColor=(Q=D.border)!=null?Q:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let m=(I=s.closeButtonSize)!=null?I:"32px",g=v("div",""),u=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");u.style.height=m,u.style.width=m,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=r?"":"none",u.style.color=s.closeButtonColor||Ir.actionIconColor;let h=(R=s.closeButtonIconName)!=null?R:"x",y=he(h,"28px","currentColor",1);y?u.appendChild(y):u.textContent="\xD7",o&&u.addEventListener("click",o),g.appendChild(u),i.appendChild(g);let E=v("div");E.style.display="none";let T=v("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},tl={default:fp,minimal:mp},gp=e=>{var t;return(t=tl[e])!=null?t:tl.default},Ga=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=v("div");p.style.display="none";let m=v("span"),g=v("span"),u=v("button");u.style.display="none";let h=v("div");return h.style.display="none",{header:d,iconHolder:p,headerTitle:m,headerSubtitle:g,closeButton:u,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=gp(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0: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 rl=e=>{var s,i;let t=v("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}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}},ol=e=>{var C,S,M,W,I,R,D,O,Q,me,ue,Z;let t=(C=e==null?void 0:e.sendButton)!=null?C:{},r=(S=t.useIcon)!=null?S:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(I=t.tooltipText)!=null?I:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",c=(O=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?O:"Send",d=(me=(Q=e==null?void 0:e.copy)==null?void 0:Q.stopButtonLabel)!=null?me:"Stop",p=(ue=t.showTooltip)!=null?ue:!1,m=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,u=t.textColor,h=v("div","persona-send-button-wrapper"),y=Tt("button",{className:bs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!g&&"persona-bg-persona-primary",!r&&!u&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?m:void 0,height:r?m:void 0,minWidth:r?m:void 0,minHeight:r?m:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?u||"var(--persona-button-primary-fg, #ffffff)":u||void 0,backgroundColor:r&&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,T=null;if(r){let Le=parseFloat(m)||24,He=(u==null?void 0:u.trim())||"currentColor";n?(E=he(n,Le,He,2),E?y.appendChild(E):y.textContent=o):y.textContent=o,T=he(a,Le,He,2)}else y.textContent=c;let A=null;p&&s&&(A=v("div","persona-send-button-tooltip"),A.textContent=s,h.appendChild(A)),y.setAttribute("aria-label",s),h.appendChild(y);let k="send";return{button:y,wrapper:h,setMode:Le=>{if(Le===k)return;k=Le;let He=Le==="stop"?i:s;if(y.setAttribute("aria-label",He),A&&(A.textContent=He),r){if(E&&T){let ie=Le==="stop"?T:E;y.replaceChildren(ie)}}else y.textContent=Le==="stop"?d:c}}},nl=e=>{var A,k,w,C,S,M,W,I,R,D,O,Q;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(o||n))return null;let s=(C=(w=e==null?void 0:e.sendButton)==null?void 0:w.size)!=null?C:"40px",i=(S=t.iconName)!=null?S:"mic",c=(M=t.iconSize)!=null?M:s,d=parseFloat(c)||24,p=(I=t.backgroundColor)!=null?I:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,m=(D=t.iconColor)!=null?D:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,g=v("div","persona-send-button-wrapper"),u=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),y=he(i,d,m||"currentColor",1.5);y?u.appendChild(y):u.textContent="\u{1F3A4}",g.appendChild(u);let E=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Q=t.showTooltip)!=null?Q:!1)&&E){let me=v("div","persona-send-button-tooltip");me.textContent=E,g.appendChild(me)}return{button:u,wrapper:g}},al=e=>{var h,y,E,T,A,k,w,C;let t=(h=e==null?void 0:e.attachments)!=null?h:{};if(t.enabled!==!0)return null;let r=(E=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?E:"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 n=v("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((T=t.allowedTypes)!=null?T:on).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(k=t.buttonIconName)!=null?k:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=v("div","persona-send-button-wrapper"),p=Tt("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":(w=t.buttonTooltipText)!=null?w:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let m=he(a,c,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",S=>{S.preventDefault(),n.click()}),d.appendChild(p);let g=(C=t.buttonTooltipText)!=null?C:"Attach file",u=v("div","persona-send-button-tooltip");return u.textContent=g,d.appendChild(u),{button:p,wrapper:d,input:n,previewsContainer:o}},sl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=v("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},il=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ka=e=>{var h,y,E,T,A,k;let{config:t}=e,r=Tt("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(),n=Tt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=rl(t);s();let i=ol(t),c=nl(t),d=al(t),p=sl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let m=Tt("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"),u=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),c&&u.append(c.wrapper),u.append(i.wrapper),m.append(g,u),n.append(m),n.addEventListener("click",w=>{w.target!==i.button&&w.target!==i.wrapper&&w.target!==(c==null?void 0:c.button)&&w.target!==(c==null?void 0:c.wrapper)&&w.target!==(d==null?void 0:d.button)&&w.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(y=c==null?void 0:c.wrapper)!=null?y:null,statusText:p,attachmentButton:(E=d==null?void 0:d.button)!=null?E:null,attachmentButtonWrapper:(T=d==null?void 0:d.wrapper)!=null?T:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(k=d==null?void 0:d.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var dx=()=>{let e=Tt("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"),r=he("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=v("span","persona-pill-peek__text"),n=v("span","persona-pill-peek__caret"),a=he("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},cx=e=>{var h,y,E,T,A,k;let{config:t}=e,r=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=il();o.style.display="none";let n=sl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=rl(t);a.style.maxHeight="100px",s();let i=ol(t),c=nl(t),d=al(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=v("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&m.append(d.wrapper);let g=v("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&g.append(c.wrapper),g.append(i.wrapper),p.addEventListener("click",w=>{w.target!==i.button&&w.target!==i.wrapper&&w.target!==(c==null?void 0:c.button)&&w.target!==(c==null?void 0:c.wrapper)&&w.target!==(d==null?void 0:d.button)&&w.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&p.append(d.input),p.append(m,a,g),d&&r.append(d.previewsContainer),r.append(p,o,n);let u=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(y=c==null?void 0:c.wrapper)!=null?y:null,statusText:n,attachmentButton:(E=d==null?void 0:d.button)!=null?E:null,attachmentButtonWrapper:(T=d==null?void 0:d.wrapper)!=null?T:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(k=d==null?void 0:d.previewsContainer)!=null?k:null,actionsRow:u,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var px=e=>{var p,m,g,u,h,y,E,T,A,k,w,C,S,M,W,I,R;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,r=or(e);if(On(e)){let D=(u=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?u:{},O=v("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(h=D.expandedSize)!=null?h:"anchored",O.style.zIndex=String((E=(y=e==null?void 0:e.launcher)==null?void 0:y.zIndex)!=null?E:Sr);let Q=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Q.style.width="100%",O.appendChild(Q);let me=v("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(T=D.expandedSize)!=null?T:"anchored",me.style.zIndex=String((k=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?k:Sr),{wrapper:O,panel:Q,pillRoot:me}}if(r){let D=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return D.appendChild(O),{wrapper:D,panel:O}}if(!t){let D=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Q=(C=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?C:"100%";return D.style.width=Q,O.style.width="100%",D.appendChild(O),{wrapper:D,panel:O}}let n=(S=e==null?void 0:e.launcher)!=null?S:{},a=n.position&&vo[n.position]?vo[n.position]:vo["bottom-right"],s=v("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?W:Sr);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?R:e==null?void 0:e.launcherWidth,d=c!=null?c:Gr;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},_v=(e,t)=>{var w,C,S,M,W,I,R,D,O;let r=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Yi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(S=(C=(w=e==null?void 0:e.launcher)==null?void 0:w.clearChat)==null?void 0:C.enabled)!=null?S:!0,s=null,i=null;if(a){let Q=Zi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Q.button,i=Q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Tt("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 p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),m=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),u=v("div","persona-flex persona-flex-col persona-gap-3"),h=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;h&&(u.style.maxWidth=h,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,u);let E=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=cx({config:e}),{root:A,textNode:k}=dx();return r.append(c,n,d,E),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:u,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:m,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:c,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:A,peekTextNode:k}},ux=(e,t=!0)=>{var E,T,A,k,w,C,S,M,W;if(On(e))return _v(e,t);let r=Tt("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=e==null?void 0:e.layout)==null?void 0:E.header,n=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,a=o?Ga(e,o,{showClose:t}):nn({config:e,showClose:t}),s=Tt("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 i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),c=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(C=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?C:"Ask anything about your account or products."}),d=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:or(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=v("div","persona-flex persona-flex-col persona-gap-3"),m=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,p);let u=Ka({config:e}),h=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;n?fa(r,a,e):(a.header.style.display="none",fa(r,a,e)),r.append(s);let y=Tt("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||(u.footer.style.display="none"),r.append(u.footer),r.append(y),{container:r,body:s,messagesWrapper:p,composerOverlay:y,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:i,introSubtitle:c,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:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var hp=(e,t)=>{let r=v("button");r.type="button",r.innerHTML=`
|
|
19
|
+
_Details: ${n.message}_`:o}var Da=e=>({isError:!0,content:[{type:"text",text:e}]}),ym=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,xm=e=>uo(e)||e===En,Hr=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 tr(()=>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&&(uo(n.name)||n.name===En&&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 Zo(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||id().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Wa(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Co.isSupported()?new Co({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 id().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=vo(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,...t};if(!zx(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Zo(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:a,id:s,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=t,f={id:s??(n==="user"?Ir():n==="assistant"?xo():`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,S={id:p??(r==="user"?Ir():r==="assistant"?xo():`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(S)}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(`
|
|
20
|
+
|
|
21
|
+
`),s=[a,n].filter(Boolean).join(`
|
|
22
|
+
|
|
23
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];a&&c.push(bo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(bo(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=Ir(),a=xo();this.activeAssistantMessageId=null;let s=n?.contentParts&&ti(n.contentParts)?ei:"",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=ld(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=xo();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=ld(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],S=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:S||"*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!==En?!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===En)return{dedupeKey:u,resumeKey:f,output:Zl(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let S=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),E;if(!S)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await S}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,Da(M?"Aborted by cancel()":ym(k)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Da("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===En?{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,Da("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(S){this.callbacks.onError?.(S instanceof Error?S:new Error(String(S)))}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===En,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=Zl():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,Da("Aborted by cancel()"),s);return}let S=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,S,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let S=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||S||p.aborted)&&this.markWebMcpToolComplete(t,Da(S||p.aborted?"Aborted by cancel()":ym(h)),s),S||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}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Jo(this.config.features?.artifacts,t.artifactType),r=Ds(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),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})}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(()=>(hm(),gm)).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=>ld(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=xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){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=ad(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Br(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=ad(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&&xm(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&&xm(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 dd=[["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 cd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var pd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var ud=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var fd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var md=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var gd=[["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 hd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var yd=[["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 xd=[["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 bd=[["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 vd=[["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 Cd=[["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 wd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Ad=[["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 Sd=[["path",{d:"M20 6 9 17l-5-5"}]];var Md=[["path",{d:"m6 9 6 6 6-6"}]];var Td=[["path",{d:"m15 18-6-6 6-6"}]];var Ed=[["path",{d:"m9 18 6-6-6-6"}]];var kd=[["path",{d:"m18 15-6-6-6 6"}]];var ai=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Ld=[["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 Pd=[["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 Rd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var ii=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Id=[["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 Bd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Hd=[["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 Wd=[["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 li=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var di=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Dd=[["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 Fd=[["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 Nd=[["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 Od=[["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 Ud=[["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 qd=[["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 Vd=[["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 zd=[["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 $d=[["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 jd=[["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 Gd=[["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 ci=[["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 Kd=[["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 Xd=[["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 Jd=[["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 Qd=[["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 Yd=[["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 Zd=[["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 pi=[["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 ec=[["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 tc=[["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 nc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var oc=[["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 rc=[["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 ui=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var ac=[["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 sc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var ic=[["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 lc=[["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 dc=[["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 cc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var pc=[["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 uc=[["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 fc=[["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 mc=[["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 gc=[["path",{d:"M5 12h14"}]];var hc=[["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 yc=[["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 xc=[["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 bc=[["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 vc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Cc=[["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 wc=[["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 Ac=[["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 Sc=[["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 Mc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Tc=[["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 Ec=[["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 kc=[["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 Lc=[["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 Pc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Rc=[["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 Ic=[["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 Bc=[["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 Hc=[["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 Wc=[["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 fi=[["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 Dc=[["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 Fc=[["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 Nc=[["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 Oc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var mi=[["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 _c=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Uc=[["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 qc=[["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 Vc=[["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 zc=[["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 $c=[["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 jc=[["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 Gc=[["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 Kc=[["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 Xc=[["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 gi=[["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 Jc=[["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 Qc=[["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 Yc=[["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 Zc=[["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 ep=[["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 tp=[["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 np=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var op=[["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 $x={activity:dd,"arrow-down":cd,"arrow-up":md,"arrow-up-right":fd,bot:bd,"chevron-down":Md,"chevron-up":kd,"chevron-right":Ed,"chevron-left":Td,check:Sd,clipboard:Pd,"clipboard-copy":Ld,"code-xml":ii,copy:Id,file:qd,"file-code":Od,"file-spreadsheet":_d,"file-text":Ud,"image-plus":ec,loader:ac,"loader-circle":ui,mic:fc,paperclip:bc,"refresh-cw":Ec,search:Pc,send:Rc,"shield-alert":Hc,"shield-check":Wc,"shield-x":fi,square:_c,"thumbs-down":$c,"thumbs-up":jc,upload:Qc,"volume-2":Zc,x:np,user:Yc,mail:ic,phone:Ac,calendar:wd,clock:Rd,building:vd,"map-pin":lc,lock:sc,key:oc,"credit-card":Bd,"at-sign":gd,hash:Jd,globe:Xd,link:rc,"circle-check":ai,"circle-x":si,"triangle-alert":gi,info:nc,ban:hd,shield:Dc,"arrow-left":pd,"arrow-right":ud,"external-link":Fd,ellipsis:di,"ellipsis-vertical":li,menu:cc,house:pi,plus:Mc,minus:gc,pencil:Cc,trash:Xc,"trash-2":Kc,save:Lc,download:Wd,share:Bc,funnel:ci,settings:Ic,"rotate-cw":kc,maximize:dc,minimize:mc,"shopping-cart":Nc,"shopping-bag":Fc,package:xc,truck:Jc,tag:zc,gift:Kd,receipt:Tc,wallet:tp,store:qc,"dollar-sign":Hd,percent:wc,play:Sc,pause:vc,"volume-x":ep,camera:Ad,image:tc,film:zd,headphones:Qd,"message-circle":pc,"message-square":uc,bell:yd,heart:Yd,star:Uc,eye:Nd,"eye-off":Dd,bookmark:xd,"calendar-days":Cd,history:Zd,timer:Gc,folder:Gd,"folder-open":jd,files:Vd,sparkles:mi,zap:op,sun:Vc,moon:yc,flag:$d,monitor:hc,smartphone:Oc},ne=(e,t=24,n="currentColor",o=2)=>{let r=$x[e];return r?jx(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 jx(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 hi={allowedTypes:Xn,maxFileSize:10*1024*1024,maxFiles:4};function Gx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Kx(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 nr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??hi.allowedTypes,maxFileSize:t.maxFileSize??hi.maxFileSize,maxFiles:t.maxFiles??hi.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:hi.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=cm(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=ni(n)?URL.createObjectURL(n):null,s={id:Gx(),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=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let s=y("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=y("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=Kx(t.file.type),p=ne(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=y("span");c.textContent=pm(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=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let a=ne("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 bm=/\s/;function Xx(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===""||bm.test(o)}function Jx(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 Xx(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
|
|
25
|
+
`||s==="\uFFFC"||!r&&bm.test(s))return null;a--}return null}function vm(e,t,n){for(let o of n){let r=Jx(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Cm(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function wm(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]}function Am(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=y("div","persona-send-button-wrapper"),c=De("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=ne(s,a,"currentColor",1.5);d?c.appendChild(d):c.textContent="+",c.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),p.appendChild(c);let u=y("div","persona-send-button-tooltip");return u.textContent=l,p.appendChild(u),{button:c,wrapper:p}}var{setLoader:Qx,load:Yx}=Sr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Sm=Qx,rp=Yx;var{setLoader:Zx,load:eb}=Sr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Mm=Zx,Tm=eb;function Fa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=De("span",{className:$n("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=ne(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=y("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(De("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Em(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=wm(t).filter(A=>A.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(A=>A.sources.some(w=>typeof w.matchCommand=="function")),r=A=>o.some(w=>w.trigger?w.position==="line-start"?A.split(`
|
|
26
|
+
`).some(R=>R.startsWith(w.trigger)):(w.position==="anywhere"?A:A.split(`
|
|
27
|
+
`)[0]).startsWith(w.trigger):!1),a=(A,w)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:w}))}catch{}},s=De("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 A=rp().then(w=>(l=w.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(w=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",w),p===A&&(p=null),null));return p=A,A},S=()=>{Tm().then(A=>{let w=A.mountInlineComposer({textarea:e.textarea,renderToken:R=>Fa(R,{render:t.renderMentionToken}),onMentionRemoved:R=>l?.untrackMention(R)});d=w.input,u=w.destroy;let T=c;T.replaceWith(w.element),c=w.element,f={next:w.element,prev:T},g?.(w.element,T),l?l.rebindComposer(w.input):p&&p.then(R=>R?.rebindComposer(w.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&S();let E=[],k=new Map;for(let A of n){if(!A.showButton)continue;let w=Am({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(A.trigger))}});E.push(w),k.set(A.trigger,w.button)}let M=(A,w,T)=>{let R=k.get(w);R&&(R.setAttribute("aria-expanded",A?"true":"false"),A?R.setAttribute("aria-controls",T):R.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:s,handleInput:A=>{if(l){l.handleInput();return}if(!Cm(A))return;let w=c,T=w.selectionStart??0;vm(w.value,T,n)&&h().then(R=>R?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){let w=c,T=w.selectionStart===0&&w.selectionEnd===0;if((w.value.length===0||T)&&l.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(l??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>l?.clear(),prefetch:()=>{rp().catch(()=>{})},onComposerSwap:A=>{g=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of E)A.wrapper.remove();s.remove()}}}var km=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Na(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];km(a)&&km(r)?n[o]=Na(a,r):n[o]=r}return n}var pn="min(440px, calc(100vw - 24px))",yi="440px",tb={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)"},pt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:tb,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 Lm(e,t){if(!(!e&&!t))return e?t?Na(e,t):e:t}function xi(e){return e?{...pt,...e,theme:Lm(pt.theme,e.theme),darkTheme:Lm(pt.darkTheme,e.darkTheme),launcher:{...pt.launcher,...e.launcher,dock:{...pt.launcher?.dock,...e.launcher?.dock},clearChat:{...pt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...pt.copy,...e.copy},sendButton:{...pt.sendButton,...e.sendButton},statusIndicator:{...pt.statusIndicator,...e.statusIndicator},voiceRecognition:{...pt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=pt.features?.artifacts,n=e.features?.artifacts,o=pt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=pt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=pt.features?.streamAnimation,p=e.features?.streamAnimation,c=pt.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},S=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...pt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...S!==void 0?{askUserQuestion:S}:{}}})(),suggestionChips:e.suggestionChips??pt.suggestionChips,suggestionChipsConfig:{...pt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...pt.layout,...e.layout,header:{...pt.layout?.header,...e.layout?.header},messages:{...pt.layout?.messages,...e.layout?.messages,avatar:{...pt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...pt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...pt.layout?.slots,...e.layout?.slots}},markdown:{...pt.markdown,...e.markdown,options:{...pt.markdown?.options,...e.markdown?.options}},messageActions:{...pt.messageActions,...e.messageActions}}:pt}var bi="16px",vi="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"}},ip={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:pn,maxWidth:yi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:bi,canvasBackground:vi},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"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 Jt(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."))?Jt(e,o):o}function Ci(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=Jt(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 lp(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 Pm(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]=Pm(a,r):n[o]=r}return n}function nb(e,t){return t?Pm(e,t):e}function Wr(e,t={}){let n={palette:ap,semantic:sp,components:ip},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:nb(n.components,e?.components)};if(t.validate!==!1){let r=lp(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 wi(e){let t=Ci(e),n={};for(let[b,W]of Object.entries(t)){let F=b.replace(/\./g,"-");n[`--persona-${F}`]=W.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"]??bi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??vi,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 b=f.toolbar;b.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=b.iconHoverColor),b.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=b.iconHoverBackground),b.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=b.iconPadding),b.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=b.iconBorderRadius),b.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=b.iconBorder),b.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=b.toggleGroupGap),b.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=b.toggleBorderRadius),b.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=b.toggleGroupPadding),b.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=b.toggleGroupBorder),b.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=b.toggleGroupBorderRadius),b.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Jt(e,b.toggleGroupBackground)??b.toggleGroupBackground),b.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=b.copyBackground),b.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=b.copyBorder),b.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=b.copyColor),b.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=b.copyBorderRadius),b.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=b.copyPadding),b.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=b.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??b.copyMenuBackground),b.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=b.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??b.copyMenuBorder),b.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=b.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??b.copyMenuShadow),b.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=b.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??b.copyMenuBorderRadius),b.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=b.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??b.copyMenuItemHoverBackground),b.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=b.iconBackground),b.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=b.toolbarBorder)}if(f?.tab){let b=f.tab;b.background&&(n["--persona-artifact-tab-bg"]=b.background),b.activeBackground&&(n["--persona-artifact-tab-active-bg"]=b.activeBackground),b.activeBorder&&(n["--persona-artifact-tab-active-border"]=b.activeBorder),b.borderRadius&&(n["--persona-artifact-tab-radius"]=b.borderRadius),b.textColor&&(n["--persona-artifact-tab-color"]=b.textColor),b.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=b.hoverBackground),b.listBackground&&(n["--persona-artifact-tab-list-bg"]=b.listBackground),b.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=b.listBorderColor),b.listPadding&&(n["--persona-artifact-tab-list-padding"]=b.listPadding)}if(f?.pane){let b=f.pane;if(b.toolbarBackground){let W=Jt(e,b.toolbarBackground)??b.toolbarBackground;n["--persona-artifact-toolbar-bg"]=W}}if(f?.card){let b=f.card;b.background&&(n["--persona-artifact-card-bg"]=b.background),b.border&&(n["--persona-artifact-card-border"]=b.border),b.borderRadius&&(n["--persona-artifact-card-radius"]=b.borderRadius),b.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=b.hoverBackground),b.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=b.hoverBorderColor)}if(f?.inline){let b=f.inline;b.background&&(n["--persona-artifact-inline-bg"]=Jt(e,b.background)??b.background),b.border&&(n["--persona-artifact-inline-border"]=b.border),b.borderRadius&&(n["--persona-artifact-inline-radius"]=b.borderRadius),b.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Jt(e,b.chromeBackground)??b.chromeBackground),b.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Jt(e,b.chromeBorder)??b.chromeBorder),b.titleColor&&(n["--persona-artifact-inline-title-color"]=Jt(e,b.titleColor)??b.titleColor),b.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Jt(e,b.mutedColor)??b.mutedColor),b.frameHeight&&(n["--persona-artifact-inline-frame-height"]=b.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"]=Jt(e,h.background)??h.background));let S=n["--persona-surface"],E=n["--persona-container"],k=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",w=!E||E===S,T=w?k:E,R=w?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"]??R,w&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),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 Rm={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 ob={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"}}},Im=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oa=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",rb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Oa()},Ai=e=>rb(e),ab=e=>Wr(e),sb=e=>{let t=Wr(void 0,{validate:!1});return Wr({...e,palette:{...t.palette,colors:{...ob.colors,...e?.palette?.colors}}},{validate:!1})},wo=e=>{let t=Ai(e),n=Im(e?.theme),o=Im(e?.darkTheme);return t==="dark"?sb(Na(n??{},o??{})):ab(n)},ib=e=>wi(e),or=(e,t)=>{let n=wo(t),o=ib(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Ai(t))},Dr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Oa())});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(Oa());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 Wn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Bm(e){let t=Wn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Si(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
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 _a(e){let t=Bm(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Ao(e){switch(_a(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Bm(e.path);return t?t.toUpperCase():"File"}}}function Hm(e){let t=e.markdown??"";return e.file?{filename:Wn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Si(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var dp="http://www.w3.org/2000/svg";function Wm(e){let t=document.createElementNS(dp,"svg");t.setAttribute("class",$n("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(dp,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(dp,"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 So=(e,t,n)=>{let o=n;for(let r of t){let a=y("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function Dm(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)),So(e,t,0)}var cp="persona-artifact-status-label",Fm="persona-artifact-status-detail",Nm="data-artifact-status-label",pp=new Map,Om=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Fr(e){e&&pp.delete(e)}function lb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Ao(t):e.artifactType==="component"?"Component":"Document"}function Nr(e,t,n){let o=lb(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=pp.get(s);e.status!=="complete"&&l===void 0&&(l=Om(),pp.set(s,l));let p=l===void 0?0:Math.max(0,Om()-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 S=a(h);return typeof S=="string"?{label:S}:S&&typeof S=="object"&&typeof S.label=="string"?{label:S.label,detail:typeof S.detail=="string"?S.detail:void 0}:{label:r}}catch{return{label:r}}}function db(e){e.className=cp,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 rr(e,t,n){let o=e.querySelector(`:scope > .${cp}`);o||(o=y("span",cp),e.appendChild(o)),o.getAttribute(Nm)!==t.label&&(db(o),Dm(o,t.label,n),o.setAttribute(Nm,t.label));let r=e.querySelector(`:scope > .${Fm}`),a=t.detail;a?(r||(r=y("span",Fm),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var cb={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"},pb=15e4,Mi={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 ub(e,t){let n=(e||"").trim().toLowerCase();if(n&&Mi[n])return Mi[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Mi[r])return Mi[r]}}return null}function Ti(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 fb=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"]),mb=[{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=>fb.has(e)?"keyword":"plain"}];function _m(e){return Ti(e,mb)}var gb=[{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 hb(e){let t=Ti(e,gb);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 yb=[{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 Um(e){let t=Ti(e,yb),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 xb=[{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 bb(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 Ti(p,xb))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),S=d==="script"?_m(h):Um(h);for(let E of S)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 vb(e,t){switch(t){case"html":return bb(e);case"css":return Um(e);case"js":return _m(e);case"json":return hb(e)}}function Cb(e){let t=Wf(),n=y("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=cb[r];if(s){let l=y("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
|
+
`);for(let s=0;s<a.length;s+=1)s>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
32
|
+
`)),n=y("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function qm(e,t,n){let o=e.length<=pb?ub(t,n):null,r=o?vb(e,o):[{type:"plain",value:e}];return Cb(r)}var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,Mo=zt+1;function To(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=y("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(Mo)):(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=ne(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let S=document.createElement("span");S.textContent=f.label,h.appendChild(S),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 kt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=y("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=ne(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 Jn(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=y("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=ne(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=y("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 Or(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=y("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=kt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{s=d.id,p(),o(d.id)}}):(u=y("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 Ei(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=y("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=y("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=ne(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=To({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 ki="persona-artifact-custom-action-btn";function _r(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 "+ki+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+ki+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Jn({icon:e.icon,label:e.label,className:ki+(n?" persona-artifact-doc-copy-btn":"")}):o=kt({icon:e.icon,label:e.label,className:ki+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ua(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 Vm(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?Wn(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=n?Ao(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 d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let h=t?.config?.features?.artifacts,S={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},E=Nr(S,h,"card");rr(f,E,h)}else a&&Fr(a),f.textContent=p;if(u.append(g,f),c.append(d,u),s==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let E={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let k of h)try{if(k.visible===void 0||k.visible(E)){let M=_r(k);M.setAttribute("data-artifact-custom-action",k.id),M.className=`${M.className} persona-flex-shrink-0`,c.append(M)}}catch{}}let S=Jn({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",a),c.append(S)}return c}var Li=(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:()=>Vm(e,t)});if(l)return l}return Vm(e,t)};var Eo=new WeakMap;function up(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=Eo.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function Km(e){return Eo.has(e)}function wb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let a=e.componentProps,s=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:s}}let r=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:"",...r?{file:r}:{}}}function zm(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Wn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Ao(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ab(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 $m=180,Sb=240,Mb=.8,Tb=300,Eb=500,kb="cubic-bezier(0.2, 0, 0, 1)",jm=240,Lb=.35;function Pb(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:$m,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(Eb,Math.max(Tb,Sb+c*Mb))),u=Math.round(d*Lb),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:jm,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:kb});e.style.height=`${p}px`;let S=!1,E=()=>{S||(S=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(d,u+jm)+120)},$m)}function Rb(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 qa="--persona-artifact-inline-body-height";function Ib(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 Gm(e,t){let n=wb(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=Rb(o),p=o?.inlineActions??[],c=Ib(o),d=c.completeDisplay==="card",u=null,g=n,f=y("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Z=>Li(Ab(Z),t),S=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(qa),f.replaceChildren(h(Z)),Eo.set(f,de=>{f.replaceChildren(h(de))})};if(d&&n.status==="complete")return S(n),f;let E=Pi(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),k=y("div","persona-artifact-inline-body");k.appendChild(E.el);let M=Z=>{let de=Z.status!=="complete",Y=de?c.streamingHeight:c.completeHeight,ve=typeof Y=="number";ve?f.style.setProperty(qa,`${Y}px`):f.style.removeProperty(qa);let we=!!E.el.querySelector(".persona-code-pre"),xe=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",we),k.classList.toggle("persona-artifact-inline-body--sized",ve&&xe),k.classList.toggle("persona-artifact-inline-body--cap",!de&&!xe&&typeof c.completeHeight=="number")},A=n.status,w=(Z,de)=>{A!=="complete"&&Z.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(qa,`${c.completeHeight}px`):f.style.removeProperty(qa),Jm(k,de?.suppressTransition?"none":c.transition,Z.id,()=>{E.update(Z),M(Z)})):E.update(Z),M(Z),A=Z.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 ${zm(n).title} in panel`)),!r)return f.appendChild(k),Eo.set(f,w),f;let R=y("div","persona-artifact-inline-chrome");R.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let b=y("div","persona-artifact-inline-chrome-lead"),W=y("span","persona-flex persona-items-center persona-flex-shrink-0"),F=ne("file-text",16,"currentColor",2);F&&W.appendChild(F);let $=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),N=y("span","persona-artifact-inline-type");b.append(W,$,N);let U=y("div","persona-artifact-inline-chrome-actions"),fe=y("span","persona-flex persona-items-center persona-gap-1"),pe=()=>u??c.viewMode,Ee=l?Or({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:pe(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let de=Z==="source"?"source":"rendered";de!==pe()&&(u=de,E.update(g),M(g))}}):null,Fe=a?kt({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 se=s?kt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(fe),Ee&&U.appendChild(Ee.element),Fe&&U.appendChild(Fe),se&&U.appendChild(se),R.append(b,U),f.append(R,k);let be=Z=>{let{title:de,typeLabel:Y}=zm(Z);$.textContent=de,$.title=de,T&&k.setAttribute("aria-label",`Open ${de} in panel`);let ve=Z.status!=="complete";if(ve){N.classList.contains("persona-artifact-inline-status")||(N.className="persona-artifact-inline-status",N.removeAttribute("data-preserve-animation"),N.replaceChildren());let we=Nr(Z,o,"inline-chrome");rr(N,we,o)}else Fr(Z.id),N.className="persona-artifact-inline-type",N.removeAttribute("data-preserve-animation"),N.replaceChildren(),N.textContent=Y;if(Fe&&Fe.classList.toggle("persona-hidden",ve),Ee){let we=Z.artifactType==="markdown"?Z.file:void 0,xe=!1;if(!ve&&we&&c.viewMode!=="source"){let He=_a(we);He==="markdown"?xe=!0:(He==="html"||He==="svg")&&(xe=o?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!xe),Ee.setSelected(pe())}if(fe.replaceChildren(),!ve&&p.length>0){let we=Ua(Z);if(we)for(let xe of p)try{if(xe.visible===void 0||xe.visible(we)){let He=_r(xe,{documentChrome:!0});He.setAttribute("data-artifact-custom-action",xe.id),He.classList.add("persona-flex-shrink-0"),fe.appendChild(He)}}catch{}}};return be(n),Eo.set(f,(Z,de)=>{if(d&&A!=="complete"&&Z.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let ve=Z,we=!1,xe=He=>{ve=He,we=!0};Eo.set(f,xe),Pb(f,Y,{swap:()=>{S(ve),we=!1,Eo.set(f,xe)},onSettled:()=>{we?S(ve):Eo.set(f,He=>{f.replaceChildren(h(He))})}});return}(Z.status!=="complete"||Z.id!==g.id)&&(u=null),g=Z,w(Z,de),be(Z)}),f}var Xm=(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:()=>Gm(e,t)});if(l)return l}return Gm(e,t)};var fp=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)})}},kn=new fp;kn.register("PersonaArtifactCard",Li,{bubbleChrome:!1});kn.register("PersonaArtifactInline",Xm,{bubbleChrome:!1});function Va(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Si(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var mp=!1;function Bb(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Jm(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"||mp||a){o();return}mp=!0;let s=Bb(n);e.style.setProperty("view-transition-name",s);let l=()=>{mp=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Hb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Wb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Db(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Fb(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 Nb=220;function Ob(){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 _b(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 Ub(e,t,n){let o=y("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=y("div","persona-artifact-frame-loading-indicator");r.appendChild(Wm());let a=null;return n.label!==!1&&(a=y("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 qb(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(A=>clearTimeout(A)),c.clear()},u=(A,w)=>{let T=setTimeout(()=>{c.delete(T),A()},w);c.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let A=Ub(r,a,o);s=A.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Nb))},S=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",M)},E=()=>{if(p||(p=!0,S(),d(),!s))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(h,A):h()};function k(A){if(n===null)return;let w=A.data;!w||w.persona!=="artifact-preview-ready"||w.token!==n||A.source===t.contentWindow&&E()}function M(){let A=w=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>w()):setTimeout(w,0)};A(()=>A(()=>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(),S(),g()}}function Pi(e,t){let{config:n}=t,o=t.registry??kn,r=t.bodyLayout,a=n.markdown?Xo(n.markdown):null,s=Tr(n.sanitize),l=e,p=!1,c=se=>{let be=zn()!==null;a&&!be&&!p&&(p=!0,Mr(()=>Fe(l)));let Z=a?a(se):Bn(se);return a&&be&&s?s(Z):Z},d=y("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},S=null,E=null,k=null,M=!1,A=()=>{S=null,E=null,k=null,M=!1},w=null,T=null,R=()=>{w=null,T=null},b=40,W=0,F=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),$=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=b,N=se=>{if(!r)return;let be=se.scrollHeight-se.clientHeight>1,Z=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",r.fadeTop&&be&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&be&&Z>1)},U=se=>{W||(W=F(()=>{W=0,se.scrollTop=se.scrollHeight,N(se)}))},fe=(se,be,Z,de)=>{let Y=!!r,ve=Z.id+"|"+(Y?"w":"p");if(!S||k!==ve||S.parentElement!==d){h(),R(),d.replaceChildren();let He=y("pre",Hb+" persona-code-pre"),Oe=y("code","persona-code");if(He.appendChild(Oe),Y){let Xe=y("div","persona-artifact-source-window");if(Xe.appendChild(He),d.appendChild(Xe),!(r?.overflow==="clip")&&typeof Xe.addEventListener=="function"){let ke=()=>Xe.scrollHeight-Xe.clientHeight>1;Xe.addEventListener("scroll",()=>{$(Xe)&&(M=!1),N(Xe)},{passive:!0}),Xe.addEventListener("wheel",Ie=>{ke()&&Ie.deltaY<0&&(M=!0)},{passive:!0}),Xe.addEventListener("touchmove",()=>{ke()&&(M=!0)},{passive:!0})}S=Xe}else d.appendChild(He),S=He;E=Oe,k=ve}let we=Y?S:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",de),we.classList.toggle("persona-artifact-source-window--clip",de&&r?.overflow==="clip"));let xe=we?$(we):!0;if(E.replaceChildren(qm(se,be?.language,be?.path)),we){let He=Z.status!=="complete";de&&He&&r?.followOutput&&!M&&xe?U(we):He||(M=!1),N(we)}},pe=se=>{h(),A(),R(),d.replaceChildren();let be=y("div",Wb);be.innerHTML=c(se),d.appendChild(be)},Ee=se=>{let be=se.id,Z=n.features?.artifacts,de=Nr(se,Z,"status-body");if(w&&T===be&&w.parentElement===d){let we=w.querySelector(".persona-artifact-status-view-text");we&&rr(we,de,Z);return}h(),A(),d.replaceChildren();let Y=y("div","persona-artifact-status-view"),ve=y("div","persona-artifact-status-view-text");rr(ve,de,Z),Y.appendChild(ve),d.appendChild(Y),w=Y,T=be},Fe=se=>{l=se;let be=t.resolveViewMode?.(se)??r?.viewMode??"rendered",Z=se.artifactType==="markdown"?se.file:void 0,de=se.status!=="complete";de||Fr(se.id);let Y=de?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&de){Ee(se);return}if(Z){let xe=Si(se.markdown??""),He=_a(Z),Oe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!de&&be==="rendered"&&Oe&&(He==="html"||He==="svg")){let qe=se.id+"\0"+xe;if(u&&g===qe&&u.parentElement===d)return;A(),R(),h(),d.replaceChildren();let ke=n.features?.artifacts?.filePreview,Ie=ke?.iframeSandbox??"allow-scripts";!ke?.dangerouslyAllowSameOrigin&&Ie.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."),Ie=Ie.split(/\s+/).filter(Lt=>Lt&&Lt!=="allow-same-origin").join(" "));let it=Fb(ke?.loading),_e=y("div","persona-artifact-frame"),Qe=y("iframe","persona-artifact-iframe");Qe.setAttribute("sandbox",Ie),Qe.setAttribute("data-artifact-id",se.id);let fn=null;it.enabled&&it.injectReadySignal?(fn=Ob(),Qe.srcdoc=xe+_b(fn)):Qe.srcdoc=xe,_e.appendChild(Qe),d.appendChild(_e),it.enabled&&(f=qb(_e,Qe,fn,it,se.id,n)),u=_e,g=qe;return}if(h(),!de&&He==="markdown"&&be==="rendered"){pe(xe);return}fe(xe,{language:Z.language,path:Z.path},se,ve);return}if(se.artifactType==="markdown"){if(be==="source"){h(),fe(se.markdown??"",void 0,se,ve);return}pe(se.markdown??"");return}h(),A(),R(),d.replaceChildren();let we=se.component?o.get(se.component):void 0;if(we){let He={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Oe=we(se.props??{},He);if(Oe){d.appendChild(Oe);return}}catch{}}d.appendChild(Db(se))};return Fe(e),{el:d,update(se){Fe(se)}}}var Qm=(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 S=u(f),E=c(g,S,h),k=r(E,()=>l(E,g,S,M=>M.morphStyle==="innerHTML"?(a(M,g,S),Array.from(g.childNodes)):o(M,g,S)));return E.pantry.remove(),k}function o(g,f,h){let S=u(f);return a(g,S,h,f,f.nextSibling),Array.from(S.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:S,selectionStart:E,selectionEnd:k}=h,M=f();return S&&S!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${S}"]`),h?.focus()),h&&!h.selectionEnd&&k&&h.setSelectionRange(E,k),M}let a=(function(){function g(w,T,R,b=null,W=null){T instanceof HTMLTemplateElement&&R instanceof HTMLTemplateElement&&(T=T.content,R=R.content),b||(b=T.firstChild);for(let F of R.childNodes){if(b&&b!=W){let N=h(w,F,b,W);if(N){N!==b&&E(w,b,N),s(N,F,w),b=N.nextSibling;continue}}if(F instanceof Element){let N=F.getAttribute("id");if(w.persistentIds.has(N)){let U=k(T,N,b,w);s(U,F,w),b=U.nextSibling;continue}}let $=f(T,F,b,w);$&&(b=$.nextSibling)}for(;b&&b!=W;){let F=b;b=b.nextSibling,S(w,F)}}function f(w,T,R,b){if(b.callbacks.beforeNodeAdded(T)===!1)return null;if(b.idMap.has(T)){let W=document.createElement(T.tagName);return w.insertBefore(W,R),s(W,T,b),b.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(T,!0);return w.insertBefore(W,R),b.callbacks.afterNodeAdded(W),W}}let h=(function(){function w(b,W,F,$){let N=null,U=W.nextSibling,fe=0,pe=F;for(;pe&&pe!=$;){if(R(pe,W)){if(T(b,pe,W))return pe;N===null&&(b.idMap.has(pe)||(N=pe))}if(N===null&&U&&R(pe,U)&&(fe++,U=U.nextSibling,fe>=2&&(N=void 0)),b.activeElementAndParents.includes(pe))break;pe=pe.nextSibling}return N||null}function T(b,W,F){let $=b.idMap.get(W),N=b.idMap.get(F);if(!N||!$)return!1;for(let U of $)if(N.has(U))return!0;return!1}function R(b,W){let F=b,$=W;return F.nodeType===$.nodeType&&F.tagName===$.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===$.getAttribute?.("id"))}return w})();function S(w,T){if(w.idMap.has(T))A(w.pantry,T,null);else{if(w.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),w.callbacks.afterNodeRemoved(T)}}function E(w,T,R){let b=T;for(;b&&b!==R;){let W=b;b=b.nextSibling,S(w,W)}return b}function k(w,T,R,b){let W=b.target.getAttribute?.("id")===T&&b.target||b.target.querySelector(`[id="${T}"]`)||b.pantry.querySelector(`[id="${T}"]`);return M(W,b),A(w,W,R),W}function M(w,T){let R=w.getAttribute("id");for(;w=w.parentNode;){let b=T.idMap.get(w);b&&(b.delete(R),b.size||T.idMap.delete(w))}}function A(w,T,R){if(w.moveBefore)try{w.moveBefore(T,R)}catch{w.insertBefore(T,R)}else w.insertBefore(T,R)}return g})(),s=(function(){function g(M,A,w){return w.ignoreActive&&M===document.activeElement?null:(w.callbacks.beforeNodeMorphed(M,A)===!1||(M instanceof HTMLHeadElement&&w.head.ignore||(M instanceof HTMLHeadElement&&w.head.style!=="morph"?p(M,A,w):(f(M,A,w),k(M,w)||a(w,M,A))),w.callbacks.afterNodeMorphed(M,A)),M)}function f(M,A,w){let T=A.nodeType;if(T===1){let R=M,b=A,W=R.attributes,F=b.attributes;for(let $ of F)E($.name,R,"update",w)||R.getAttribute($.name)!==$.value&&R.setAttribute($.name,$.value);for(let $=W.length-1;0<=$;$--){let N=W[$];if(N&&!b.hasAttribute(N.name)){if(E(N.name,R,"remove",w))continue;R.removeAttribute(N.name)}}k(R,w)||h(R,b,w)}(T===8||T===3)&&M.nodeValue!==A.nodeValue&&(M.nodeValue=A.nodeValue)}function h(M,A,w){if(M instanceof HTMLInputElement&&A instanceof HTMLInputElement&&A.type!=="file"){let T=A.value,R=M.value;S(M,A,"checked",w),S(M,A,"disabled",w),A.hasAttribute("value")?R!==T&&(E("value",M,"update",w)||(M.setAttribute("value",T),M.value=T)):E("value",M,"remove",w)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&A instanceof HTMLOptionElement)S(M,A,"selected",w);else if(M instanceof HTMLTextAreaElement&&A instanceof HTMLTextAreaElement){let T=A.value,R=M.value;if(E("value",M,"update",w))return;T!==R&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function S(M,A,w,T){let R=A[w],b=M[w];if(R!==b){let W=E(w,M,"update",T);W||(M[w]=A[w]),R?W||M.setAttribute(w,""):E(w,M,"remove",T)||M.removeAttribute(w)}}function E(M,A,w,T){return M==="value"&&T.ignoreActiveValue&&A===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,A,w)===!1}function k(M,A){return!!A.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,S){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 A=Object.assign(g,{head:{block:!1,ignore:!0}});return S(A)})}}return S(g)}function p(g,f,h){let S=[],E=[],k=[],M=[],A=new Map;for(let T of f.children)A.set(T.outerHTML,T);for(let T of g.children){let R=A.has(T.outerHTML),b=h.head.shouldReAppend(T),W=h.head.shouldPreserve(T);R||W?b?E.push(T):(A.delete(T.outerHTML),k.push(T)):h.head.style==="append"?b&&(E.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&E.push(T)}M.push(...A.values());let w=[];for(let T of M){let R=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(R)!==!1){if("href"in R&&R.href||"src"in R&&R.src){let b,W=new Promise(function(F){b=F});R.addEventListener("load",function(){b()}),w.push(W)}g.appendChild(R),h.callbacks.afterNodeAdded(R),S.push(R)}}for(let T of E)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:S,kept:k,removed:E}),w}let c=(function(){function g(w,T,R){let{persistentIds:b,idMap:W}=M(w,T),F=f(R),$=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:w,newContent:T,config:F,morphStyle:$,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:W,persistentIds:b,pantry:h(),activeElementAndParents:S(w),callbacks:F.callbacks,head:F.head}}function f(w){let T=Object.assign({},t);return Object.assign(T,w),T.callbacks=Object.assign({},t.callbacks,w.callbacks),T.head=Object.assign({},t.head,w.head),T}function h(){let w=document.createElement("div");return w.hidden=!0,document.body.insertAdjacentElement("afterend",w),w}function S(w){let T=[],R=document.activeElement;if(R?.tagName!=="BODY"&&w.contains(R))for(;R&&(T.push(R),R!==w);)R=R.parentElement;return T}function E(w){let T=Array.from(w.querySelectorAll("[id]"));return w.getAttribute?.("id")&&T.push(w),T}function k(w,T,R,b){for(let W of b){let F=W.getAttribute("id");if(T.has(F)){let $=W;for(;$;){let N=w.get($);if(N==null&&(N=new Set,w.set($,N)),N.add(F),$===R)break;$=$.parentElement}}}}function M(w,T){let R=E(w),b=E(T),W=A(R,b),F=new Map;k(F,W,w,R);let $=T.__idiomorphRoot||T;return k(F,W,$,b),{persistentIds:W,idMap:F}}function A(w,T){let R=new Set,b=new Map;for(let{id:F,tagName:$}of w)b.has(F)?R.add(F):b.set(F,$);let W=new Set;for(let{id:F,tagName:$}of T)W.has(F)?R.add(F):b.get(F)===$&&W.add(F);for(let F of R)W.delete(F);return W}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 S(k);{let M=document.createElement("div");return M.append(k),M}}else{let M=document.createElement("div");for(let A of[...k])M.append(A);return M}}class S{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],A=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;A&&A!=this.nextSibling;)M.push(A),A=A.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((A,w)=>{if(w instanceof Element){w.matches(M)&&A.push(w);let T=w.querySelectorAll(M);for(let R=0;R<T.length;R++)A.push(T[R])}return A},[])}insertBefore(M,A){return this.realParentNode.insertBefore(M,A)}moveBefore(M,A){return this.realParentNode.moveBefore(M,A)}get __idiomorphRoot(){return this.originalNode}}function E(k){let M=new DOMParser,A=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(A.match(/<\/html>/)||A.match(/<\/head>/)||A.match(/<\/body>/)){let w=M.parseFromString(k,"text/html");if(A.match(/<\/html>/))return g.add(w),w;{let T=w.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 Ri=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Qm.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 Ym=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var gp={index:-1,draft:""};function Zm(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 eg(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 tg(){return new Map}function ng(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function og(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function rg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ii(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Dn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ko(e,t){return Dn(e)-e.scrollTop<=t}function Bi(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 Hi(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 ag(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sg(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 ig(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var za={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Vb=["pre","code","a","script","style"],Wi=e=>({type:e?.type??za.type,placeholder:e?.placeholder??za.placeholder,speed:e?.speed??za.speed,duration:e?.duration??za.duration,buffer:e?.buffer??za.buffer}),dg=[{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"}],$a=new Map;for(let e of dg)$a.set(e.name,e);var ar=e=>{$a.set(e.name,e)},xp=e=>{dg.some(t=>t.name===e)||$a.delete(e)},bp=()=>Array.from($a.keys()),Ur=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:$a.get(e)??null,Di=(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},zb=(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},$b=(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/,jb=(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},Gb=(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(zb(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},Kb=(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($b(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},ja=(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??Vb).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)jb(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?Gb:Kb;for(let u of l)d(u,n,c);return r.innerHTML},Fi=(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},Ga=(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},lg=new WeakMap,Xb=(e,t)=>{if(!e.styles)return;let n=lg.get(t);if(n||(n=new Set,lg.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)},yp=new WeakMap,Jb=(e,t)=>{if(!e.onAttach)return;let n=yp.get(t);if(n||(n=new Map,yp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},cg=e=>{let t=yp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ni=(e,t)=>{Xb(e,t),Jb(e,t)};function vp(e,t=zt){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 Ka=0,Lo=null;function Cp(e=document){if(Ka++,Ka===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Lo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Ka=Math.max(0,Ka-1),Ka===0&&Lo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Lo.originalOverflow,n.style.position=Lo.originalPosition,n.style.top=Lo.originalTop,n.style.width=Lo.originalWidth,o.scrollTo(0,Lo.scrollY),Lo=null}}}var Xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},It=e=>(e?.launcher?.mountMode??"floating")==="docked",Po=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",on=e=>{let t=e?.launcher?.dock;return{side:t?.side??Xa.side,width:t?.width??Xa.width,animate:t?.animate??Xa.animate,reveal:t?.reveal??Xa.reveal,maxHeight:t?.maxHeight??Xa.maxHeight}};var Ln={"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 Qb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Oi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Qb,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=y("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=De("button",{className:$n("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||Qt.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}}),S=ne(u,a,"currentColor",1);if(S?(S.style.display="block",h.appendChild(S)):h.textContent=g,p.appendChild(h),d&&c){let E=null,k=()=>{if(E)return;let A=h.ownerDocument,w=A.body;if(!w)return;E=Hn(A,"div","persona-clear-chat-tooltip"),E.textContent=c;let T=Hn(A,"div");T.className="persona-clear-chat-tooltip-arrow",E.appendChild(T);let R=h.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(Mo),E.style.left=`${R.left+R.width/2}px`,E.style.top=`${R.top-8}px`,E.style.transform="translate(-50%, -100%)",w.appendChild(E)},M=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};p.addEventListener("mouseenter",k),p.addEventListener("mouseleave",M),h.addEventListener("focus",k),h.addEventListener("blur",M),p._cleanupTooltip=()=>{M(),p.removeEventListener("mouseenter",k),p.removeEventListener("mouseleave",M),h.removeEventListener("focus",k),h.removeEventListener("blur",M)}}return{button:h,wrapper:p}},Yb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",_i=(e,t={})=>{let{wrapperClassName:n=Yb,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??"",S=s.paddingY??"",E=s.tooltipText??"Clear chat",k=s.showTooltip??!0,M=y("div",n),A=!!(u||g),w=De("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:l,width:l,color:c||Qt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:S||void 0,paddingBottom:S||void 0}}),T=ne(p,r,"currentColor",1);if(T&&(T.style.display="block",w.appendChild(T)),M.appendChild(w),k&&E){let R=null,b=()=>{if(R)return;let F=w.ownerDocument,$=F.body;if(!$)return;R=Hn(F,"div","persona-clear-chat-tooltip"),R.textContent=E;let N=Hn(F,"div");N.className="persona-clear-chat-tooltip-arrow",R.appendChild(N);let U=w.getBoundingClientRect();R.style.position="fixed",R.style.zIndex=String(Mo),R.style.left=`${U.left+U.width/2}px`,R.style.top=`${U.top-8}px`,R.style.transform="translate(-50%, -100%)",$.appendChild(R)},W=()=>{R&&R.parentNode&&(R.parentNode.removeChild(R),R=null)};M.addEventListener("mouseenter",b),M.addEventListener("mouseleave",W),w.addEventListener("focus",b),w.addEventListener("blur",W),M._cleanupTooltip=()=>{W(),M.removeEventListener("mouseenter",b),M.removeEventListener("mouseleave",W),w.removeEventListener("focus",b),w.removeEventListener("blur",W)}}return{button:w,wrapper:M}};var Qt={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))"},Qn=e=>{let{config:t,showClose:n=!0}=e,o=De("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=De("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,R=ne(p,T*.6,"currentColor",1);R?c.replaceChildren(R):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=y("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=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=De("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Qt.titleColor}}),g=De("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,S=f.placement??"inline",E=null,k=null;if(h){let R=_i(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=R.button,k=R.wrapper,S==="top-right"&&(k.style.right="48px"),S==="inline"&&o.appendChild(k)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&S==="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:A,wrapper:w}=Oi(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(w),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:A,closeButtonWrapper:w,clearChatButton:E,clearChatButtonWrapper:k}},sr=(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 wp=e=>{let t=Qn({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 Zb(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-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=ne(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=y("div","persona-relative");a.appendChild(r);let s=To({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 Ap=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=y("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=Ei({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Qt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=y("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Qt.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),Zb(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let A=r.onTitleClick;c.addEventListener("click",w=>{w.target.closest("button")||A()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),A())})}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=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=s.closeButtonColor||Qt.actionIconColor;let h=s.closeButtonIconName??"x",S=ne(h,"28px","currentColor",1);S?f.appendChild(S):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let E=y("div");E.style.display="none";let k=y("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:d,headerSubtitle:k,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Ui={default:wp,minimal:Ap},Sp=e=>Ui[e]??Ui.default,qr=(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=y("div");l.style.display="none";let p=y("span"),c=y("span"),d=y("button");d.style.display="none";let u=y("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=Sp(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 qi=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let 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}},Vi=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=y("div","persona-send-button-wrapper"),S=De("button",{className:$n("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 T=parseFloat(u)||24,R=f?.trim()||"currentColor";r?(E=ne(r,T,R,2),E?S.appendChild(E):S.textContent=o):S.textContent=o,k=ne(a,T,R,2)}else S.textContent=p;let M=null;d&&s&&(M=y("div","persona-send-button-tooltip"),M.textContent=s,h.appendChild(M)),S.setAttribute("aria-label",s),h.appendChild(S);let A="send";return{button:S,wrapper:h,setMode:T=>{if(T===A)return;A=T;let R=T==="stop"?l:s;if(S.setAttribute("aria-label",R),M&&(M.textContent=R),n){if(E&&k){let b=T==="stop"?k:E;S.replaceChildren(b)}}else S.textContent=T==="stop"?c:p}}},zi=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=y("div","persona-send-button-wrapper"),f=De("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor: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}}),S=ne(l,c,u||"currentColor",1.5);S?f.appendChild(S):f.textContent="\u{1F3A4}",g.appendChild(f);let E=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&E){let M=y("div","persona-send-button-tooltip");M.textContent=E,g.appendChild(M)}return{button:f,wrapper:g}},$i=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Xn).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=y("div","persona-send-button-wrapper"),d=De("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=ne(a,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",h=>{h.preventDefault(),r.click()}),c.appendChild(d);let g=t.buttonTooltipText??"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:d,wrapper:c,input:r,previewsContainer:o}},ji=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=y("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},Gi=()=>De("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Vr=e=>{let{config:t}=e,n=De("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=Gi(),r=De("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=qi(t);s();let l=Vi(t),p=zi(t),c=$i(t),d=ji(t);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(a);let u=De("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return 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 pg=()=>{let e=De("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ne("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),a=ne("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=De("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Gi(),r=ji(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=qi(t);a.style.maxHeight="100px",s();let l=Vi(t),p=zi(t),c=$i(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=De("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let g=y("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 fg=e=>{let t=e?.launcher?.enabled??!0,n=It(e);if(Po(e)){let d=e?.launcher?.composerBar??{},u=y("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??zt);let g=y("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=y("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??zt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("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=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("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&&Ln[r.position]?Ln[r.position]:Ln["bottom-right"],s=y("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??zt);let l=y("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}},ev=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Oi(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 w=_i(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=w.button,l=w.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=De("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=De("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=De("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=De("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=De("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=y("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=De("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:A}=pg();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:y("span"),headerTitle:y("span"),headerSubtitle:y("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:A}},mg=(e,t=!0)=>{if(Po(e))return ev(e,t);let n=De("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?qr(e,o,{showClose:t}):Qn({config:e,showClose:t}),s=De("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=De("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=De("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=De("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:It(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=y("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=Vr({config:e}),h=e?.layout?.showFooter!==!1;r?sr(n,a,e):(a.header.style.display="none",sr(n,a,e)),n.append(s);let S=De("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(S),{container:n,body:s,messagesWrapper:d,composerOverlay:S,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 Mp=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
21
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>
|
|
22
36
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
23
37
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -25,14 +39,14 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
25
39
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
26
40
|
</span>
|
|
27
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>
|
|
28
|
-
`,r.addEventListener("click",t);let o=a=>{var k,w,C,S,M,W,I,R,D,O,Q,me,ue;let s=(k=a.launcher)!=null?k:{},i=or(a),c=r.querySelector("[data-role='launcher-title']");if(c){let Z=(w=s.title)!=null?w:"Chat Assistant";c.textContent=Z,c.setAttribute("title",Z)}let d=r.querySelector("[data-role='launcher-subtitle']");if(d){let Z=(C=s.subtitle)!=null?C:"Here to help you get answers fast";d.textContent=Z,d.setAttribute("title",Z)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let m=r.querySelector("[data-role='launcher-icon']");if(m)if(s.agentIconHidden)m.style.display="none";else{let Z=(S=s.agentIconSize)!=null?S:"40px";if(m.style.height=Z,m.style.width=Z,s.agentIconBackgroundColor?(m.style.backgroundColor=s.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",s.agentIconName){let Le=parseFloat(Z)||24,He=he(s.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);He?(m.appendChild(He),m.style.display=""):(m.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",m.style.display="")}else s.iconUrl?m.style.display="none":(m.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}let g=r.querySelector("[data-role='launcher-image']");if(g){let Z=(I=s.agentIconSize)!=null?I:"40px";g.style.height=Z,g.style.width=Z,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let u=r.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let Z=(R=s.callToActionIconSize)!=null?R:"32px";u.style.height=Z,u.style.width=Z,s.callToActionIconBackgroundColor?(u.style.backgroundColor=s.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(u.style.color=s.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let Le=0;if(s.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=s.callToActionIconPadding,Le=(parseFloat(s.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),s.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",s.callToActionIconName){let He=parseFloat(Z)||24,ie=Math.max(He-Le,8),Me=he(s.callToActionIconName,ie,"currentColor",2);Me?u.appendChild(Me):u.textContent=(D=s.callToActionIconText)!=null?D:"\u2197"}else u.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let h=s.position&&vo[s.position]?vo[s.position]:vo["bottom-right"],y="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";r.className=i?E:`${y} ${h}`,i||(r.style.zIndex=String((Q=s.zIndex)!=null?Q:Sr));let T="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))";r.style.border=(me=s.border)!=null?me:T,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ue=s.collapsedMaxWidth)!=null?ue:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var fx=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=px(e),a=ux(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={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:i,header:c,composer:d,replaceHeader:g=>(c.element.replaceWith(g.header),c.element=g.header,c.iconHolder=g.iconHolder,c.headerTitle=g.headerTitle,c.headerSubtitle=g.headerSubtitle,c.closeButton=g.closeButton,c.closeButtonWrapper=g.closeButtonWrapper,c.clearChatButton=g.clearChatButton,c.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{d.footer.replaceWith(g),d.footer=g}}},xp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>hp(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=hp(e,r);return{instance:n,element:n.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 r=Uv(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Vv=(e,t)=>{let r=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},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(":"))},yp=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(":"))},bp=320,gx=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,t,r)=>{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 n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var m;let d=v("img");d.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${bp}px`,d.style.maxHeight=`${gx}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 p=!1;n+=1,d.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),d.remove(),n===0&&s())}),d.addEventListener("load",()=>{p=!0}),zv(i.image)?(d.src=i.image,o.appendChild(d)):(p=!0,n=Math.max(0,n-1),d.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},Qv=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 r=0;return e.forEach(o=>{if(!yp(o.audio))return;let n=v("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${bp}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Jv=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 r=0;return e.forEach(o=>{if(!yp(o.video))return;let n=v("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${bp}px`,n.style.maxHeight=`${gx}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},Yv=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 r=0;return e.forEach(o=>{if(!yp(o.data))return;let n=v("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ma=()=>{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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="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 n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},vp=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:ma};if(t){let n=t(o);if(n!==null)return n}return ma()},Zv=(e,t)=>{let r=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 n=v("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},mx=(e,t,r="div")=>{let o=v(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},e0=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},wp=(e,t,r)=>{var h,y,E,T,A,k,w;let o=(h=t.showCopy)!=null?h:!0,n=(y=t.showUpvote)!=null?y:!0,a=(E=t.showDownvote)!=null?E:!0,s=(T=t.showReadAloud)!=null?T:!1;if(!o&&!n&&!a&&!s){let C=v("div");return C.style.display="none",C.id=`actions-${e.id}`,C.setAttribute("data-actions-for",e.id),C}let i=(A=t.visibility)!=null?A:"hover",c=(k=t.align)!=null?k:"right",d=(w=t.layout)!=null?w:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],m={"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 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let u=(C,S,M)=>{let W=pr({icon:C,label:S,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&g.appendChild(u("copy","Copy message","copy")),s&&g.appendChild(u("volume-2","Read aloud","read-aloud")),n&&g.appendChild(u("thumbs-up","Upvote","upvote")),a&&g.appendChild(u("thumbs-down","Downvote","downvote")),g},Xa=(e,t,r,o,n,a)=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe;let s=r!=null?r:{},i=(oe=s.layout)!=null?oe:"bubble",c=s.avatar,d=s.timestamp,p=(se=c==null?void 0:c.show)!=null?se:!1,m=(ge=d==null?void 0:d.show)!=null?ge:!1,g=(Te=c==null?void 0:c.position)!=null?Te:"left",u=(qe=d==null?void 0:d.position)!=null?qe:"below",h=e0(e.role,i),y=v("div",h.join(" "));y.id=`bubble-${e.id}`,y.setAttribute("data-message-id",e.id),y.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(y.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",y.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(y.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",y.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$v(e),T=(ee=(j=e.content)==null?void 0:j.trim())!=null?ee:"",k=E.length>0&&T===Si,w=Ki((te=(Ee=a==null?void 0:a.widgetConfig)==null?void 0:Ee.features)==null?void 0:te.streamAnimation),C=(nt=(ke=(le=a==null?void 0:a.widgetConfig)==null?void 0:le.features)==null?void 0:ke.streamAnimation)==null?void 0:nt.plugins,S=e.role==="assistant"&&w.type!=="none"?ja(w.type,C):null,M=e.role==="assistant"&&((yt=S==null?void 0:S.isAnimating)==null?void 0:yt.call(S,e))===!0,W=e.role==="assistant"&&S!==null&&(!!e.streaming||M);W&&(S!=null&&S.bubbleClass)&&y.classList.add(S.bubbleClass);let I=document.createElement("div");I.classList.add("persona-message-content"),e.streaming&&I.classList.add("persona-content-streaming"),W&&S&&(S.containerClass&&I.classList.add(S.containerClass),I.style.setProperty("--persona-stream-step",`${w.speed}ms`),I.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let R=W?Xi((Kt=e.content)!=null?Kt:"",w.buffer,S,e,!!e.streaming):(jt=e.content)!=null?jt:"",D=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=D;W&&(S==null?void 0:S.wrap)==="char"?O=Bs(D,"char",e.id,{skipTags:S.skipTags}):W&&(S==null?void 0:S.wrap)==="word"&&(O=Bs(D,"word",e.id,{skipTags:S.skipTags}));let Q=null;if(k?(Q=document.createElement("div"),Q.innerHTML=O,Q.style.display="none",I.appendChild(Q)):I.innerHTML=O,W&&(S!=null&&S.useCaret)&&!k&&T){let X=Qi(),st=I.querySelectorAll(".persona-stream-char, .persona-stream-word"),je=st[st.length-1];if(je!=null&&je.parentNode)je.parentNode.insertBefore(X,je.nextSibling);else{let Ce=I.lastElementChild;Ce?Ce.appendChild(X):I.appendChild(X)}}if(m&&u==="inline"&&e.createdAt){let X=mx(e,d,"span");X.classList.add("persona-timestamp-inline");let st=I.lastElementChild;st?st.appendChild(X):I.appendChild(X)}if(E.length>0){let X=Xv(E,!k&&!!T,()=>{k&&Q&&(Q.style.display="")});X?y.appendChild(X):k&&Q&&(Q.style.display="")}let me=jv(e);if(me.length>0){let X=Qv(me);X&&y.appendChild(X)}let ue=Gv(e);if(ue.length>0){let X=Jv(ue);X&&y.appendChild(X)}let Z=Kv(e);if(Z.length>0){let X=Yv(Z);X&&y.appendChild(X)}if(y.appendChild(I),m&&u==="below"&&e.createdAt){let X=mx(e,d);X.classList.add("persona-mt-1"),y.appendChild(X)}let Le=e.role==="assistant"?qv(e.stopReason,(fe=(ct=a==null?void 0:a.widgetConfig)==null?void 0:ct.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),st=w.placeholder==="skeleton",je=st&&w.buffer==="line"&&X;if(X)je&&y.appendChild(Ds());else if(st)y.appendChild(Ds());else{let Ce=vp("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);Ce&&y.appendChild(Ce)}}if(Le&&e.stopReason&&!e.streaming&&(T||(I.style.display="none"),y.appendChild(Vv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let X=wp(e,o,n);y.appendChild(X)}if(!p||e.role==="system")return y;let ie=v("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Me=Zv(c,e.role);return g==="right"||g==="left"&&e.role==="user"?ie.append(y,Me):ie.append(Me,y),y.classList.remove("persona-max-w-[85%]"),y.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ie},hx=(e,t,r,o,n,a)=>{let s=r!=null?r:{};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}):Xa(e,t,r,o,n,a)};var Qa=new Set,t0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),r0=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
29
|
-
`):""},
|
|
30
|
-
`);let
|
|
31
|
-
`):""},Sp=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},a0=(e,t)=>{var p,m,g,u,h;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(m=o==null?void 0:o.collapsedMode)!=null?m:"tool-call",a=n0(e,(g=o==null?void 0:o.previewMaxLines)!=null?g:3),s=r?vh(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(u=t==null?void 0:t.toolCall)!=null?u:{},d=s;return n==="tool-name"?d=((h=r.name)==null?void 0:h.trim())||s:n==="tool-preview"&&a&&(d=a),i&&c.activeTextTemplate?d=td(r,c.activeTextTemplate,d):!i&&c.completeTextTemplate&&(d=td(r,c.completeTextTemplate,d)),{summary:d,previewText:a,isActive:i}},yx=(e,t,r)=>{var p;let o=Ja.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=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"),d=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let m=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",g=he(o?"chevron-up":"chevron-down",16,m,2);g?d.appendChild(g):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ap=(e,t)=>{var O,Q,me,ue,Z,Le,He,ie,Me;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.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))",!r)return n;let a=(me=(Q=t==null?void 0:t.features)==null?void 0:Q.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&Ja.has(e.id),{summary:c,previewText:d,isActive:p}=a0(e,t),m=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");m.type="button",s&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let g=v("div","persona-flex persona-flex-col persona-text-left"),u=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(u.style.color=o.headerTextColor);let h=String((ue=r.startedAt)!=null?ue:Date.now()),y=()=>{let oe=v("span","");return oe.setAttribute("data-tool-elapsed",h),oe.textContent=Ms(r),oe},E=(Le=o.renderCollapsedSummary)==null?void 0:Le.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:d,collapsedMode:(Z=a.collapsedMode)!=null?Z:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Ms(r),createElapsedElement:y});typeof E=="string"&&E.trim()?(u.textContent=E,g.appendChild(u)):E instanceof HTMLElement?g.appendChild(E):(u.textContent=c,g.appendChild(u));let T=(He=a.loadingAnimation)!=null?He:"none",A=o.activeTextTemplate,k=o.completeTextTemplate,w=p?A:k,C=E instanceof HTMLElement,S=(oe,se,ge)=>{let Te=ge;for(let qe of se){let j=v("span","persona-tool-char");j.style.setProperty("--char-index",String(Te)),j.textContent=qe===" "?"\xA0":qe,oe.appendChild(j),Te++}return Te},M=(oe,se)=>{var j;u.textContent="";let ge=((j=r.name)==null?void 0:j.trim())||"tool",Te=xi(oe,ge),qe=0;for(let ee of Te){let Ee=ee.styles.length>0?(()=>{let te=v("span",ee.styles.map(le=>`persona-tool-text-${le}`).join(" "));return u.appendChild(te),te})():u;if(ee.isDuration&&p)Ee.appendChild(y());else{let te=ee.isDuration?Ms(r):ee.text;se?qe=S(Ee,te,qe):Ee.appendChild(document.createTextNode(te))}}};if(!C)if(p&&T!=="none"){let oe=(ie=o.loadingAnimationDuration)!=null?ie:2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),w&&M(w,!1);else if(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),T==="shimmer-color"&&(o.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),w)M(w,!0);else{let se=u.textContent||c;u.textContent="",S(u,se,0)}}else w&&M(w,!1);let W=null;if(s){W=v("div","persona-flex persona-items-center");let oe=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=he(i?"chevron-up":"chevron-down",16,oe,2);se?W.appendChild(se):W.textContent=i?"Hide":"Show";let ge=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ge.append(W),m.append(g,ge)}else m.append(g);let I=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","tool"),I.style.display="none",I.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&d){let oe=(Me=o.renderCollapsedPreview)==null?void 0:Me.call(o,{message:e,toolCall:r,defaultPreview:d,isActive:p,config:t!=null?t:{}});o0(I,oe)||(I.textContent=d),I.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(m,I),n;let R=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",o.contentBackgroundColor&&(R.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(R.style.color=o.contentTextColor),o.contentPaddingX&&(R.style.paddingLeft=o.contentPaddingX,R.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(R.style.paddingTop=o.contentPaddingY,R.style.paddingBottom=o.contentPaddingY),r.name){let oe=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?oe.style.color=o.contentTextColor:o.headerTextColor&&(oe.style.color=o.headerTextColor),oe.textContent=r.name,R.appendChild(oe)}if(r.args!==void 0){let oe=v("div","persona-space-y-1"),se=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Arguments";let ge=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");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Sp(ge,o),ge.textContent=Rn(r.args),oe.append(se,ge),R.appendChild(oe)}if(r.chunks&&r.chunks.length){let oe=v("div","persona-space-y-1"),se=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Activity";let ge=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");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Sp(ge,o),ge.textContent=r.chunks.join(""),oe.append(se,ge),R.appendChild(oe)}if(r.status==="complete"&&r.result!==void 0){let oe=v("div","persona-space-y-1"),se=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(se.style.color=o.labelTextColor),se.textContent="Result";let ge=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");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Sp(ge,o),ge.textContent=Rn(r.result),oe.append(se,ge),R.appendChild(oe)}if(r.status==="complete"&&typeof r.duration=="number"){let oe=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(oe.style.color=o.contentTextColor),oe.textContent=`Duration: ${r.duration}ms`,R.appendChild(oe)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let oe=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",se=he(i?"chevron-up":"chevron-down",16,oe,2);se?W.appendChild(se):W.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",I.style.display=i?"none":I.textContent||I.childNodes.length?"":"none"})(),n.append(m,I,R),n};var ga=new Map,ll=e=>{let r=(e.startsWith(yo)?e.slice(yo.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},bx=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,vx=(e,t)=>{var o,n,a;let r=(n=(o=bx(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=ga.get(e))!=null?a:r==="expanded"},wx=(e,t,r)=>{var s,i;let o=bx(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=he(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Cx=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=vx(e,r);wx(o,a,r),n.style.display=a?"":"none"};var dl=(e,t)=>{var M,W,I,R,D,O,Q,me,ue,Z,Le,He,ie,Me,oe;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(M=o==null?void 0:o.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(W=o==null?void 0:o.borderColor)!=null?W:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",d=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(I=o==null?void 0:o.titleColor)!=null?I:"currentColor",p=he(c,20,d,2);p&&i.appendChild(p);let m=v("div","persona-flex-1 persona-min-w-0"),g=v("div","persona-flex persona-items-center persona-gap-2"),u=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(u.style.color=o.titleColor),u.textContent=(R=o==null?void 0:o.title)!=null?R:"Approval Required",g.appendChild(u),!n){let se=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",r.status),r.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):r.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):r.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),g.appendChild(se)}m.appendChild(g);let y=r.toolType==="webmcp"||r.toolName.startsWith(yo)?ys(r.toolName):void 0,E=(D=o==null?void 0:o.formatDescription)==null?void 0:D.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...y?{displayTitle:y}:{},...r.reason?{reason:r.reason}:{}}),T=!r.toolName,A=E||(T?r.description:`The assistant wants to use \u201C${y!=null?y:ll(r.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=A,m.appendChild(k),r.reason){let se=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?se.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(se.style.color=o.descriptionColor);let ge=v("span","persona-font-medium");ge.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(ge),se.appendChild(document.createTextNode(r.reason)),m.appendChild(se)}let w=(Q=o==null?void 0:o.detailsDisplay)!=null?Q:"collapsed",C=!!r.description&&!T,S=C||!!r.parameters;if(w!=="hidden"&&S){let se=vx(e.id,t),ge=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");ge.type="button",ge.setAttribute("data-expand-header","true"),ge.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(ge.style.color=o.descriptionColor);let Te=v("span");Te.setAttribute("data-approval-details-label","true");let qe=v("span","persona-inline-flex persona-items-center");qe.setAttribute("data-approval-details-chevron","true"),ge.append(Te,qe),wx(ge,se,t),m.appendChild(ge);let j=v("div");if(j.setAttribute("data-approval-details","true"),j.style.display=se?"":"none",C){let ee=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(ee.style.color=o.descriptionColor),ee.textContent=r.description,j.appendChild(ee)}if(r.parameters){let ee=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!=null&&o.parameterBackgroundColor&&(ee.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(ee.style.color=o.parameterTextColor),ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",ee.textContent=Rn(r.parameters),j.appendChild(ee)}m.appendChild(j)}if(n){let se=v("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ge=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");ge.type="button",ge.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",ge.style.color=(ue=o==null?void 0:o.approveButtonTextColor)!=null?ue:"#ffffff",ge.setAttribute("data-approval-action","approve");let Te=he("shield-check",14,(Z=o==null?void 0:o.approveButtonTextColor)!=null?Z:"#ffffff",2);Te&&(Te.style.marginRight="4px",ge.appendChild(Te));let qe=document.createTextNode((Le=o==null?void 0:o.approveLabel)!=null?Le:"Approve");ge.appendChild(qe);let j=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");j.type="button",j.style.backgroundColor=(He=o==null?void 0:o.denyButtonColor)!=null?He:"transparent",j.style.color=(ie=o==null?void 0:o.denyButtonTextColor)!=null?ie:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let ee=he("shield-x",14,(Me=o==null?void 0:o.denyButtonTextColor)!=null?Me:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",j.appendChild(ee));let Ee=document.createTextNode((oe=o==null?void 0:o.denyLabel)!=null?oe:"Deny");j.appendChild(Ee),se.append(ge,j),m.appendChild(se)}return s.append(i,m),a.appendChild(s),a};function s0(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function Sx(e){var y;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,d=(y=e.container)!=null?y:s0(t),p=!1,m=null,g=()=>{if(!p)return;let E=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${E.width}px`);let T=o==="top-start"||o==="top-end"?E.top-n-r.getBoundingClientRect().height:E.bottom+n,A=o==="bottom-end"||o==="top-end"?E.right-r.getBoundingClientRect().width:E.left;r.style.top=`${T}px`,r.style.left=`${A}px`},u=()=>{p&&(p=!1,m&&(m(),m=null),r.remove())},h=()=>{var C,S,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),d.appendChild(r),g();let E=(S=((C=t.ownerDocument)!=null?C:document).defaultView)!=null?S:window,T=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){u(),c==null||c("anchor-removed");return}g()},k=W=>{let I=typeof W.composedPath=="function"?W.composedPath():[];I.includes(r)||I.includes(t)||(u(),c==null||c("outside"))},w=E.setTimeout(()=>{T.addEventListener("pointerdown",k,!0)},0);E.addEventListener("scroll",A,!0),E.addEventListener("resize",A),m=()=>{E.clearTimeout(w),T.removeEventListener("pointerdown",k,!0),E.removeEventListener("scroll",A,!0),E.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:h,close:u,toggle:()=>p?u():h(),reposition:g,destroy:u}}function Ax(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var i0=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Mx=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},ha=(e,t)=>{Mx(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},l0=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,d0=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=ga.get(e))!=null?n:r==="expanded"},Mp=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},c0=(e,t)=>{var d,p;let r=v("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(yo)?ys(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(d=e.description)!=null?d:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:ll(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let m=document.createElement("strong");m.textContent=i,r.appendChild(m)}return r},p0=e=>{let t=v("div","persona-approval-resolved"),r=he("ban",15,"currentColor",2);r&&t.appendChild(r);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?ll(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},u0=(e,t,r,o,n,a,s)=>{var W,I,R,D,O,Q,me;let i=v("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(W=o==null?void 0:o.detailsDisplay)!=null?W:"collapsed",d=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",m=d||p,g=m&&d0(t.id,o),u=(I=o==null?void 0:o.showDetailsLabel)!=null?I:"Show details",h=(R=o==null?void 0:o.hideDetailsLabel)!=null?R:"Hide details",y=v("button","persona-approval-head");y.type="button",m?(y.setAttribute("data-action","toggle-params"),y.setAttribute("aria-expanded",g?"true":"false"),y.setAttribute("aria-label",g?h:u)):y.setAttribute("data-static","true");let E=v("span","persona-approval-logo"),T=he("shield-check",16,"currentColor",2);T&&E.appendChild(T),y.appendChild(E);let A=c0(r,o);if(m){let ue=v("span","persona-approval-toggle");ue.setAttribute("aria-hidden","true");let Z=he("chevron-down",14,"currentColor",2);Z&&ue.appendChild(Z),A.append(" "),A.appendChild(ue)}y.appendChild(A),i.appendChild(y);let k=v("div","persona-approval-body");if(m){let ue=v("div","persona-approval-details");if(ue.setAttribute("data-role","params"),ue.hidden=!g,d){let Z=v("p","persona-approval-desc");o!=null&&o.descriptionColor&&(Z.style.color=o.descriptionColor),Z.textContent=r.description,ue.appendChild(Z)}if(p){let Z=v("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(Z.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(Z.style.color=o.parameterTextColor),Z.textContent=Rn(r.parameters),ue.appendChild(Z)}k.appendChild(ue)}if(r.reason){let ue=v("p","persona-approval-reason");o!=null&&o.reasonColor?ue.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ue.style.color=o.descriptionColor);let Z=v("span","persona-approval-reason-label");Z.textContent=`${(D=o==null?void 0:o.reasonLabel)!=null?D:"Agent's stated reason:"} `,ue.append(Z,document.createTextNode(r.reason)),k.appendChild(ue)}let w=v("div","persona-approval-actions"),C=null,S=ue=>{o!=null&&o.approveButtonColor&&(ue.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(ue.style.color=o.approveButtonTextColor)},M=v("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let ue=v("div","persona-approval-split"),Z=v("button","persona-approval-primary");Z.type="button",Z.setAttribute("data-action","always"),S(Z),Z.append((Q=o==null?void 0:o.approveLabel)!=null?Q:"Always allow",Mp("\u23CE"));let Le=v("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),S(Le);let He=he("chevron-down",15,"currentColor",2);He&&Le.appendChild(He),ue.append(Z,Le),w.append(ue,M),M.append(Mp("Esc"));let ie=v("div","persona-approval-menu"),Me=v("button","persona-approval-menu-item");Me.type="button",Me.append("Allow once",Mp("\u2318\u23CE")),ie.appendChild(Me),C=Sx({anchor:ue,content:ie,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,C),Me.addEventListener("click",()=>{ha(e,t.id),n()})}else{let ue=v("button","persona-approval-primary persona-approval-primary--solo");ue.type="button",ue.setAttribute("data-action","allow"),S(ue),ue.append((me=o==null?void 0:o.approveLabel)!=null?me:"Allow"),w.append(ue,M)}return k.appendChild(w),i.appendChild(k),i.addEventListener("click",ue=>{let Z=ue.target instanceof Element?ue.target.closest("[data-action]"):null;if(!Z)return;let Le=Z.getAttribute("data-action");if(Le==="toggle-params"){let He=i.querySelector('[data-role="params"]');if(He){let ie=He.hidden;He.hidden=!ie,y.setAttribute("aria-expanded",ie?"true":"false"),y.setAttribute("aria-label",ie?h:u),ga.set(t.id,ie)}return}if(Le==="toggle-menu"){C==null||C.toggle();return}if(Le==="always"){ha(e,t.id),n({remember:!0});return}if(Le==="allow"){ha(e,t.id),n();return}if(Le==="deny"){ha(e,t.id),a();return}}),i},Tx=()=>{let e=i0();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=l0(s);if(i.status!=="pending"){if(ha(e,o.id),i.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return p0(i)}Mx(e,o.id);let d=(c==null?void 0:c.enableAlwaysAllow)===!0,p=u0(e,o,i,c,n,a,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let m=g=>{Ax(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),ha(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,m),document.addEventListener("keydown",m)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])ha(e,o);e.latestPendingApprovalId=null}}};var Ex=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,d)=>{e.innerHTML="",t.length=0;let p=(d==null?void 0:d.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(E=>E.role==="user"))return;let m=document.createDocumentFragment(),g=a?a.isStreaming():!1,u=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(n.forEach(h=>{let y=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");y.type="button",y.textContent=h,y.disabled=g,c!=null&&c.fontFamily&&(y.style.fontFamily=u(c.fontFamily)),c!=null&&c.fontWeight&&(y.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(y.style.paddingLeft=c.paddingX,y.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(y.style.paddingTop=c.paddingY,y.style.paddingBottom=c.paddingY),y.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),m.appendChild(y),t.push(y)}),e.appendChild(m),p){let h=JSON.stringify(n);h!==r&&(r=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var _s=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;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),(r=this.store)==null||r.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 r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)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,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Us=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(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 n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{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=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{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=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{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=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(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 n of t)o.put(n)}catch{}}};var f0=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),m0=new Set(["step_start","execution_start"]),g0=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),h0=new Set(["step_complete","agent_turn_complete"]),x0=new Set(["flow_complete","agent_complete"]),kx=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Px=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,xa=(e,t)=>{let r=e[t];return Px(r)?r:void 0};function Tp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function cl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function y0(e,t){return typeof t.type=="string"?t.type:e}function b0(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 v0(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 Lx(e){var o,n,a,s,i;let t=xa(e,"result"),r=[xa(e,"tokens"),xa(e,"totalTokens"),t?xa(t,"tokens"):void 0,xa(e,"usage"),t?xa(t,"usage"):void 0];for(let c of r){if(!c)continue;let d=(n=(o=Xr(c.output))!=null?o:Xr(c.outputTokens))!=null?n:Xr(c.completionTokens);if(d!==void 0)return d}return(i=(a=Xr(e.outputTokens))!=null?a:Xr(e.completionTokens))!=null?i:t?(s=Xr(t.outputTokens))!=null?s:Xr(t.completionTokens):void 0}function w0(e){var r,o,n,a,s;let t=xa(e,"result");return(s=(n=(o=(r=Xr(e.executionTime))!=null?r:Xr(e.executionTimeMs))!=null?o:Xr(e.execution_time))!=null?n:Xr(e.duration))!=null?s:t?(a=Xr(t.executionTime))!=null?a:Xr(t.executionTimeMs):void 0}function C0(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var qs=class{constructor(t=C0){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 r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:cl(this.metric.outputTokens,r)}}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,r){var a;if(!Px(r)){kx.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=y0(t,r),n=this.now();if(f0.has(o)){this.startRun(n);return}if(m0.has(o)){this.run||this.startRun(n);return}if(g0.has(o)){if(!v0(o,r))return;let s=b0(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+Tp(i.visibleCharCount),d=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:cl(c,d),outputTokens:c,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(h0.has(o)){if(!this.run)return;let s=this.run,i=Lx(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,d=s.exactOutputTokens+Tp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:cl(d,p),outputTokens:d,durationMs:p,source:c?"usage":"estimate"};return}if(x0.has(o)){if(!this.run)return;let s=this.run,i=Lx(r),c=i!=null?i:s.exactOutputTokens+Tp(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:cl(c,p),outputTokens:c,durationMs:p,source:d},this.run=null;return}if(kx.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=w0(r);return a!=null?a:o-t.startedAt}};function Ya(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var S0={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)"}},A0={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},M0=["flowName","stepName","reasoningText","text","name","tool","toolName"],T0=100;function E0(e,t){let r={...S0,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return A0}function k0(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function L0(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function P0(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)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 R0(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function I0(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 W0(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function H0(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 B0(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=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]"),c=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function Ep(e,t,r,o,n,a,s,i){var g;let c=n.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Ya(d,(g=o.classNames)==null?void 0:g.eventRow);let p=s.find(u=>u.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let u=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(u)return d.appendChild(u),d}return d.appendChild(m()),d;function m(){var O,Q;let u=v("div",""),h=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");h.setAttribute("data-event-id",e.id);let y=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=he(c?"chevron-down":"chevron-right","14px","currentColor",2);E&&y.appendChild(E);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";T.textContent=A==="relative"?k0(e.timestamp,r):L0(e.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let w=E0(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=w.bg,C.style.color=w.text,C.style.borderColor=w.text+"50",C.textContent=e.type;let S=(Q=o.descriptionFields)!=null?Q:M0,M=P0(e.payload,S),W=null;M&&(W=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let I=v("div","persona-flex-1 persona-min-w-0"),R=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"),D=he("clipboard","12px","currentColor",1.5);return D&&R.appendChild(D),R.addEventListener("click",async me=>{me.stopPropagation(),await R0(I0(e)),R.innerHTML="";let ue=he("check","12px","currentColor",1.5);ue&&R.appendChild(ue),setTimeout(()=>{R.innerHTML="";let Z=he("clipboard","12px","currentColor",1.5);Z&&R.appendChild(Z)},1500)}),h.appendChild(y),h.appendChild(T),k&&h.appendChild(k),h.appendChild(C),W&&h.appendChild(W),h.appendChild(I),h.appendChild(R),u.appendChild(h),c&&u.appendChild(B0(e,s,i)),u}}function Rx(e){var h,y,E,T,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(h=n==null?void 0:n.features)==null?void 0:h.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,d=(y=i==null?void 0:i.iconName)!=null?y:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",m=(A=(T=n==null?void 0:n.features)==null?void 0:T.eventStream)!=null?A:{},g=a.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&n){let k=g.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>u().element,onClose:o});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return u();function u(){let k=m.classNames,w=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ya(w,k==null?void 0:k.panel);let C=[],S="",M="",W=null,I=[],R={},D=0,O=$i(),Q=0,me=0,ue=!1,Z=null,Le=!1,He=0,ie=new Set,Me=new Map,oe="",se="",ge=null,Te,qe,j,ee,Ee=null,te=null,le=null;function ke(){let pe=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),N=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(Ya(N,k==null?void 0:k.headerBar),s){te=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),te.style.cursor="help",Ee=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"),Ee.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ft=te,er=le,So=()=>{if(!er.textContent)return;let io=Ft.getBoundingClientRect(),lo=pe.getBoundingClientRect();er.style.left=`${io.left-lo.left}px`,er.style.top=`${io.bottom-lo.top+4}px`,er.style.display="block"},Uo=()=>{er.style.display="none"};te.addEventListener("mouseenter",So),te.addEventListener("mouseleave",Uo),te.appendChild(Ee)}let ye=v("div","persona-flex-1");Te=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 ae=v("option","");ae.value="",ae.textContent="All events (0)",Te.appendChild(ae),qe=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"),qe.type="button",qe.title="Copy All";let Ke=he("clipboard-copy","12px","currentColor",1.5);Ke&&qe.appendChild(Ke);let Lt=v("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",qe.appendChild(Lt),te&&N.appendChild(te),N.appendChild(ye),N.appendChild(Te),N.appendChild(qe);let Et=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ya(Et,k==null?void 0:k.searchBar);let bt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),It=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");bt&&It.appendChild(bt),j=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"),Ya(j,k==null?void 0:k.searchInput),j.type="text",j.placeholder="Search event payloads...",ee=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"),ee.type="button",ee.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&ee.appendChild(Qt),Et.appendChild(It),Et.appendChild(j),Et.appendChild(ee),pe.appendChild(N),pe.appendChild(Et),le&&pe.appendChild(le),pe}let nt,yt=a.find(pe=>pe.renderEventStreamToolbar);if(yt!=null&&yt.renderEventStreamToolbar&&n){let pe=yt.renderEventStreamToolbar({config:n,defaultRenderer:()=>ke(),eventCount:t.getSize(),filteredCount:0,onFilterChange:N=>{S=N,xe(),Ct()},onSearchChange:N=>{M=N,xe(),Ct()}});nt=pe!=null?pe:ke()}else nt=ke();let Kt=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");Kt.style.display="none";function jt(){if(!s||!Ee||!te)return;let pe=s(),N=W0(pe);Ee.textContent=N;let ye=H0(pe);le&&(le.textContent=ye,ye||(le.style.display="none")),te.setAttribute("aria-label",ye?`Throughput: ${N}, ${ye}`:`Throughput: ${N}`)}let ct=v("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let X=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ya(X,k==null?void 0:k.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let st=he(d,"14px","currentColor",2);st&&X.appendChild(st);let je=v("span","");je.textContent=p,X.appendChild(je);let Ce=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",ct.appendChild(fe),ct.appendChild(Ce),ct.appendChild(X),w.setAttribute("tabindex","0"),w.appendChild(nt),w.appendChild(Kt),w.appendChild(ct);function ve(){let pe=t.getAll(),N={};for(let Et of pe)N[Et.type]=(N[Et.type]||0)+1;let ye=Object.keys(N).sort(),ae=ye.length!==I.length||!ye.every((Et,bt)=>Et===I[bt]),mt=!ae&&ye.some(Et=>N[Et]!==R[Et]),Ke=pe.length!==Object.values(R).reduce((Et,bt)=>Et+bt,0);if(!ae&&!mt&&!Ke||(I=ye,R=N,!Te))return;let Lt=Te.value;if(Te.options[0].textContent=`All events (${pe.length})`,ae){for(;Te.options.length>1;)Te.remove(1);for(let Et of ye){let bt=v("option","");bt.value=Et,bt.textContent=`${Et} (${N[Et]||0})`,Te.appendChild(bt)}Lt&&ye.includes(Lt)?Te.value=Lt:Lt&&(Te.value="",S="")}else for(let Et=1;Et<Te.options.length;Et++){let bt=Te.options[Et];bt.textContent=`${bt.value} (${N[bt.value]||0})`}}function Ye(){let pe=t.getAll();if(S&&(pe=pe.filter(N=>N.type===S)),M){let N=M.toLowerCase();pe=pe.filter(ye=>ye.type.toLowerCase().includes(N)||ye.payload.toLowerCase().includes(N))}return pe}function Vt(){return S!==""||M!==""}function xe(){D=0,Q=0,O.resume(),X.style.display="none"}function de(pe){ie.has(pe)?ie.delete(pe):ie.add(pe),ge=pe;let N=fe.scrollTop,ye=O.isFollowing();Le=!0,O.pause(),Ct(),fe.scrollTop=N,ye&&O.resume(),Le=!1}function Ar(){return Dn(fe,50)}function Ct(){me=Date.now(),ue=!1,jt(),ve();let pe=t.getEvictedCount();pe>0?(Kt.textContent=`${pe.toLocaleString()} older events truncated`,Kt.style.display=""):Kt.style.display="none",C=Ye();let N=C.length,ye=t.getSize()>0;N===0&&ye&&Vt()?(Ce.textContent=M?`No events matching '${M}'`:"No events matching filter",Ce.style.display="",fe.style.display="none"):(Ce.style.display="none",fe.style.display=""),qe&&(qe.title=Vt()?`Copy Filtered (${N})`:"Copy All"),c&&!O.isFollowing()&&N>D&&(Q+=N-D,je.textContent=p?`${p}${Q>0?` (${Q})`:""}`:"",X.style.display=""),D=N;let ae=t.getAll(),mt=ae.length>0?ae[0].timestamp:0,Ke=new Set(C.map(bt=>bt.id));for(let bt of ie)Ke.has(bt)||ie.delete(bt);let Lt=S!==oe||M!==se,Et=Me.size===0&&C.length>0;if(Lt||Et||C.length===0){fe.innerHTML="",Me.clear();let bt=document.createDocumentFragment();for(let It=0;It<C.length;It++){let Qt=Ep(C[It],It,mt,m,ie,de,a,n);Me.set(C[It].id,Qt),bt.appendChild(Qt)}fe.appendChild(bt),oe=S,se=M,ge=null}else{if(ge!==null){let It=Me.get(ge);if(It&&It.parentNode===fe){let Qt=C.findIndex(Ft=>Ft.id===ge);if(Qt>=0){let Ft=Ep(C[Qt],Qt,mt,m,ie,de,a,n);fe.insertBefore(Ft,It),It.remove(),Me.set(ge,Ft)}}ge=null}let bt=new Set(C.map(It=>It.id));for(let[It,Qt]of Me)bt.has(It)||(Qt.remove(),Me.delete(It));for(let It=0;It<C.length;It++){let Qt=C[It];if(!Me.has(Qt.id)){let Ft=Ep(Qt,It,mt,m,ie,de,a,n);Me.set(Qt.id,Ft),fe.appendChild(Ft)}}}O.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function br(){if(Date.now()-me>=T0){Z!==null&&(cancelAnimationFrame(Z),Z=null),Ct();return}ue||(ue=!0,Z=requestAnimationFrame(()=>{Z=null,Ct()}))}let wo=(pe,N)=>{if(!qe)return;qe.innerHTML="";let ye=he(pe,"12px","currentColor",1.5);ye&&qe.appendChild(ye);let ae=v("span","persona-text-xs");ae.textContent="Copy All",qe.appendChild(ae),setTimeout(()=>{qe.innerHTML="";let mt=he("clipboard-copy","12px","currentColor",1.5);mt&&qe.appendChild(mt);let Ke=v("span","persona-text-xs");Ke.textContent="Copy All",qe.appendChild(Ke),qe.disabled=!1},N)},Co=async()=>{if(qe){qe.disabled=!0;try{let pe;Vt()?pe=C:r?(pe=await r(),pe.length===0&&(pe=t.getAll())):pe=t.getAll();let N=pe.map(ye=>{try{return JSON.parse(ye.payload)}catch{return ye.payload}});await navigator.clipboard.writeText(JSON.stringify(N,null,2)),wo("check",1500)}catch{wo("x",1500)}}},Ve=()=>{Te&&(S=Te.value,xe(),Ct())},H=()=>{!j||!ee||(ee.style.display=j.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=j.value,xe(),Ct()},150))},ce=()=>{!j||!ee||(j.value="",M="",ee.style.display="none",W&&clearTimeout(W),xe(),Ct())},Se=()=>{if(Le)return;let pe=fe.scrollTop,{action:N,nextLastScrollTop:ye}=ji({following:O.isFollowing(),currentScrollTop:pe,lastScrollTop:He,nearBottom:Ar(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});He=ye,N==="resume"?(O.resume(),Q=0,X.style.display="none"):N==="pause"&&(O.pause(),c&&(je.textContent=p,X.style.display=""))},Ae=pe=>{let N=Gi({following:O.isFollowing(),deltaY:pe.deltaY,nearBottom:Ar(),resumeWhenNearBottom:!0});N==="pause"?(O.pause(),c&&(je.textContent=p,X.style.display="")):N==="resume"&&(O.resume(),Q=0,X.style.display="none")},Ie=()=>{c&&(fe.scrollTop=fe.scrollHeight,O.resume(),Q=0,X.style.display="none")},et=pe=>{let N=pe.target;if(!N||N.closest("button"))return;let ye=N.closest("[data-event-id]");if(!ye)return;let ae=ye.getAttribute("data-event-id");ae&&de(ae)},Qe=pe=>{if((pe.metaKey||pe.ctrlKey)&&pe.key==="f"){pe.preventDefault(),j==null||j.focus(),j==null||j.select();return}pe.key==="Escape"&&(j&&document.activeElement===j?(ce(),j.blur(),w.focus()):o&&o())};qe&&qe.addEventListener("click",Co),Te&&Te.addEventListener("change",Ve),j&&j.addEventListener("input",H),ee&&ee.addEventListener("click",ce),fe.addEventListener("scroll",Se),fe.addEventListener("wheel",Ae,{passive:!0}),fe.addEventListener("click",et),X.addEventListener("click",Ie),w.addEventListener("keydown",Qe);function gt(){W&&clearTimeout(W),Z!==null&&(cancelAnimationFrame(Z),Z=null),ue=!1,Me.clear(),qe&&qe.removeEventListener("click",Co),Te&&Te.removeEventListener("change",Ve),j&&j.removeEventListener("input",H),ee&&ee.removeEventListener("click",ce),fe.removeEventListener("scroll",Se),fe.removeEventListener("wheel",Ae),fe.removeEventListener("click",et),X.removeEventListener("click",Ie),w.removeEventListener("keydown",Qe)}return{element:w,update:br,destroy:gt}}}function Ix(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${s.toLowerCase()}...`,m.appendChild(u)}else m.textContent=s;if(d.append(p,m),i.append(c,d),n==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${r}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",o),i.append(g)}return i}var Wx=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",d=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:d,status:c},config:t.config,defaultRenderer:()=>Ix(e,t)});if(p)return p}return Ix(e,t)};var kp=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,o])=>{this.register(r,o)})}},an=new kp;an.register("PersonaArtifactCard",Wx);function D0(e){var n;let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=v("div","persona-font-semibold persona-text-sm persona-mb-2");r.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((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function Hx(e,t){var qe,j,ee,Ee;let r=(j=(qe=e.features)==null?void 0:qe.artifacts)==null?void 0:j.layout,n=((ee=r==null?void 0:r.toolbarPreset)!=null?ee:"default")==="document",a=(Ee=r==null?void 0:r.panePadding)==null?void 0:Ee.trim(),s=e.markdown?aa(e.markdown):null,i=Ha(e.sanitize),c=te=>{let le=s?s(te):Fo(te);return i?i(le):le},d=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{d==null||d.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),D==null||D.hide()};d&&d.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),n&&m.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&g.classList.add("persona-artifact-toolbar-document");let u=v("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let h=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");h.type="button",h.textContent="Close",h.setAttribute("aria-label","Close artifacts panel"),h.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let y="rendered",E=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=n?pr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):pr({icon:"eye",label:"Rendered view"}),A=n?pr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):pr({icon:"code-2",label:"Source"}),k=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,C=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,S=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(C&&S&&S.length>0),W=null,I,R=null,D=null;if(n&&(w||C)&&!M){if(I=w?Os({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),C){let te=he("chevron-down",14,"currentColor",2);te&&I.appendChild(te)}}else n&&M?(W=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),I=w?Os({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=pr({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"}}),W.append(I,R)):n?I=pr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):I=pr({icon:"copy",label:"Copy"});let O=n?pr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):pr({icon:"refresh-cw",label:"Refresh"}),Q=n?pr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):pr({icon:"x",label:"Close"}),me=()=>{var yt,Kt,jt;let te=(yt=Me.find(ct=>ct.id===oe))!=null?yt:Me[Me.length-1],le=(Kt=te==null?void 0:te.id)!=null?Kt:null,ke=(te==null?void 0:te.artifactType)==="markdown"&&(jt=te.markdown)!=null?jt:"",nt=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:ke,jsonPayload:nt,id:le}},ue=async()=>{var yt;let{markdown:te,jsonPayload:le}=me(),ke=(yt=Me.find(Kt=>Kt.id===oe))!=null?yt:Me[Me.length-1],nt=(ke==null?void 0:ke.artifactType)==="markdown"?te:ke?le:"";try{await navigator.clipboard.writeText(nt)}catch{}};if(I.addEventListener("click",async()=>{let te=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(te&&M){let{markdown:le,jsonPayload:ke,id:nt}=me();try{await te({actionId:"primary",artifactId:nt,markdown:le,jsonPayload:ke})}catch{}return}await ue()}),R&&(S!=null&&S.length)){let te=()=>{var ke;return(ke=m.closest("[data-persona-root]"))!=null?ke:document.body},le=()=>{D=_n({items:S.map(ke=>({id:ke.id,label:ke.label})),onSelect:async ke=>{let{markdown:nt,jsonPayload:yt,id:Kt}=me(),jt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{jt?await jt({actionId:ke,artifactId:Kt,markdown:nt,jsonPayload:yt}):ke==="markdown"||ke==="md"?await navigator.clipboard.writeText(nt):ke==="json"||ke==="source"?await navigator.clipboard.writeText(yt):await navigator.clipboard.writeText(nt||yt)}catch{}},anchor:W!=null?W:R,position:"bottom-right",portal:te()})};m.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",ke=>{ke.stopPropagation(),D==null||D.toggle()})}O.addEventListener("click",async()=>{var te;try{await((te=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:te.call(r))}catch{}ge()}),Q.addEventListener("click",()=>{var te;p(),(te=t.onDismiss)==null||te.call(t)});let Z=()=>{n&&(T.setAttribute("aria-pressed",y==="rendered"?"true":"false"),A.setAttribute("aria-pressed",y==="source"?"true":"false"))};T.addEventListener("click",()=>{y="rendered",Z(),ge()}),A.addEventListener("click",()=>{y="source",Z(),ge()});let Le=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");n?(g.replaceChildren(),E.append(T,A),W?k.append(W,O,Q):k.append(I,O,Q),g.append(E,Le,k),Z()):(g.appendChild(u),g.appendChild(h)),a&&(g.style.paddingLeft=a,g.style.paddingRight=a);let He=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ie=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(He.style.paddingLeft=a,He.style.paddingRight=a,ie.style.padding=a),m.appendChild(g),m.appendChild(He),m.appendChild(ie);let Me=[],oe=null,se=!1,ge=()=>{var nt,yt,Kt,jt;let te=n&&Me.length<=1;He.classList.toggle("persona-hidden",te),He.replaceChildren();for(let ct of Me){let fe=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");fe.type="button",fe.textContent=ct.title||ct.id.slice(0,8),ct.id===oe&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(ct.id)),He.appendChild(fe)}ie.replaceChildren();let le=oe&&Me.find(ct=>ct.id===oe)||Me[Me.length-1];if(!le)return;if(n){let ct=le.artifactType==="markdown"?"MD":(nt=le.component)!=null?nt:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${ct}`}else u.textContent="Artifacts";if(le.artifactType==="markdown"){if(n&&y==="source"){let fe=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(yt=le.markdown)!=null?yt:"",ie.appendChild(fe);return}let ct=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ct.innerHTML=c((Kt=le.markdown)!=null?Kt:""),ie.appendChild(ct);return}let ke=le.component?an.get(le.component):void 0;if(ke){let fe={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=ke((jt=le.props)!=null?jt:{},fe);if(X){ie.appendChild(X);return}}catch{}}ie.appendChild(D0(le))},Te=()=>{var le;let te=Me.length>0;if(m.classList.toggle("persona-hidden",!te),d){let ke=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,yt=((le=ke==null?void 0:ke.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&yt&&se?(d.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:d,update(te){var le,ke,nt;Me=te.artifacts,oe=(nt=(ke=te.selectedId)!=null?ke:(le=te.artifacts[te.artifacts.length-1])==null?void 0:le.id)!=null?nt:null,Me.length>0&&(se=!0),ge(),Te()},setMobileOpen(te){se=te,!te&&d?(d.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Te()}}}function so(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Bx(e,t){var a,s,i,c;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"),!so(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function F0(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function pl(e,t){var c,d,p,m,g,u,h,y,E,T;if(!so(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"),F0(e),Bx(e,t);return}let r=(d=(c=t.features)==null?void 0:c.artifacts)==null?void 0:d.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(m=r==null?void 0:r.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=r==null?void 0:r.paneMaxWidth)!=null?g:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(u=r==null?void 0:r.paneBackground)==null?void 0:u.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(h=r==null?void 0:r.panePadding)==null?void 0:h.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(y=r==null?void 0:r.documentToolbarIconColor)==null?void 0:y.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(E=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:E.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Bx(e,t)}var Dx=["panel","seamless"];function ul(e,t){var i,c,d,p,m,g;for(let u of Dx)e.classList.remove(`persona-artifact-appearance-${u}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!so(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(d=r==null?void 0:r.paneAppearance)!=null?d:"panel",n=Dx.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(m=r==null?void 0:r.paneShadow)==null?void 0:m.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let u=((g=r.unifiedSplitOuterRadius)==null?void 0:g.trim())||a;u&&e.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Fx(e,t){var r,o,n;return!t||!so(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function N0(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function O0(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function _0(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function U0(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Nx(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Ox(e,t,r,o,n,a){let s=N0(n,200),i=U0(t,r,o,200);i=Math.max(s,i);let c=O0(a);return c!==null&&(i=Math.min(i,c)),_0(e,s,i)}var _x={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"}},Lp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var h,y,E;if(a.dataset.enhanced==="true")return;let s=(h=a.dataset.tvForm)!=null?h:"init";a.dataset.enhanced="true";let i=(y=_x[s])!=null?y:_x.init;a.classList.add("persona-form-card","persona-space-y-4");let c=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,c.appendChild(d),i.description){let T=v("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,c.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var S,M;let A=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${T.name}`;let k=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,A.appendChild(k);let w=(S=T.type)!=null?S:"text",C;w==="textarea"?(C=document.createElement("textarea"),C.rows=3):(C=document.createElement("input"),C.type=w),C.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",C.id=`${t.id}-${s}-${T.name}`,C.name=T.name,C.placeholder=(M=T.placeholder)!=null?M:"",T.required&&(C.required=!0),A.appendChild(C),p.appendChild(A)});let m=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]"),u=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");u.type="submit",u.textContent=(E=i.submitLabel)!=null?E:"Submit",m.appendChild(g),m.appendChild(u),p.appendChild(m),a.replaceChildren(c,p),p.addEventListener("submit",async T=>{var C,S;T.preventDefault();let A=(C=r.formEndpoint)!=null?C:"/form",k=new FormData(p),w={};k.forEach((M,W)=>{w[W]=M}),w.type=s,u.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();g.textContent=(S=W.message)!=null?S:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await o.sendMessage(String(W.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Pp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Vs=new Pp;var Ux=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var q0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},V0=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},zs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=q0(e),r=V0(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},Rp=e=>typeof e=="string"?e:e==null?"":String(e),ya={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Rp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=Rp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Rp(r.text)}}},qx=e=>Array.isArray(e)?e.map(t=>String(t)):[],$s=e=>{let t=new Set(qx(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(qx(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!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((d,p)=>d||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let d of e.handlers)if(d)try{let p=()=>{e.emit("action:resubmit",c)},m=d(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var z0=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},$0=e=>e.map(t=>({...t,streaming:!1})),j0=e=>e.map(t=>({...t,status:"complete"})),fl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?z0(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?$0(r.messages):void 0,artifacts:r.artifacts?j0(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Za=Ia(li(),1);function G0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function K0(e,t){if(!G0(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function ml(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,Za.parse)(r,Za.STR|Za.OBJ),a=K0(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function Vx(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:r,message:o,onPropsUpdate:n}=t,a=an.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:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function zx(){let e=ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function $x(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 js(e){let t=$x(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function hl(e){let t=$x(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var X0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function xl(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:d=X0}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,u.appendChild(h);let y=document.createElement("p");y.className="persona-feedback-subtitle",y.textContent=n,u.appendChild(y),g.appendChild(u);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 T=[];for(let S=1;S<=5;S++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${d[S-1]}`),M.title=d[S-1],M.dataset.rating=String(S),M.innerHTML=`
|
|
42
|
+
`,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=It(a),p=n.querySelector("[data-role='launcher-title']");if(p){let A=s.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let A=s.subtitle??"Here to help you get answers fast";c.textContent=A,c.setAttribute("title",A)}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 A=s.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,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 w=parseFloat(A)||24,T=ne(s.agentIconName,w*.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 A=s.agentIconSize??"40px";g.style.height=A,g.style.width=A,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 A=s.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,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 w=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,w=(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(A)||24,R=Math.max(T-w,8),b=ne(s.callToActionIconName,R,"currentColor",2);b?f.appendChild(b):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Ln[s.position]?Ln[s.position]:Ln["bottom-right"],S="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:`${S} ${h}`,l||(n.style.zIndex=String(s.zIndex??zt));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 gg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=fg(e),a=mg(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}}},Tp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Mp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Mp(e,n);return{instance:r,element:r.element}};var tv=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}},nv=(e,t)=>{if(!e)return null;let n=tv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},ov=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},rv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ep=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(":"))},kp=320,bg=320,av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),iv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),dv=e=>{if(!e||e.length===0)return null;let t=De("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=De("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),a=ne(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(De("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},cv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Fa(o.ref,{readonly:!0,render:t}))}return n},hg="\uE000",yg="\uE001",pv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${hg}${r}:${g}${yg}`,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(cv(t,o));return}e.innerHTML=l;let c=new RegExp(`${hg}${r}:(\\d+)${yg}`),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 S=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),S?.kind==="mention"&&E.parentNode?.insertBefore(Fa(S.ref,{readonly:!0,render:o}),E),f=E}}},uv=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let c=y("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=`${kp}px`,c.style.maxHeight=`${bg}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}),rv(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}},fv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Ep(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${kp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},mv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Ep(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${kp}px`,r.style.maxHeight=`${bg}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}},gv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Ep(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ir=()=>{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},Lp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ir};if(t){let r=t(o);if(r!==null)return r}return ir()},hv=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},xg=(e,t,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},yv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Pp=(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=y("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=y("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,S,E)=>{let k=kt({icon:h,label:S,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},zr=(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=yv(e.role,l),S=y("div",h.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=av(e),k=e.content?.trim()??"",A=E.length>0&&k===ei,w=Wi(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,R=e.role==="assistant"&&w.type!=="none"?Ur(w.type,T):null,b=e.role==="assistant"&&R?.isAnimating?.(e)===!0,W=e.role==="assistant"&&R!==null&&(!!e.streaming||b);W&&R?.bubbleClass&&S.classList.add(R.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),W&&R&&(R.containerClass&&F.classList.add(R.containerClass),F.style.setProperty("--persona-stream-step",`${w.speed}ms`),F.style.setProperty("--persona-stream-duration",`${w.duration}ms`));let $=W?Di(e.content??"",w.buffer,R,e,!!e.streaming):e.content??"",N=()=>{let Y=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return W&&R?.wrap==="char"?ja(Y,"char",e.id,{skipTags:R.skipTags}):W&&R?.wrap==="word"?ja(Y,"word",e.id,{skipTags:R.skipTags}):Y},U=null;if(A?(U=document.createElement("div"),U.innerHTML=N(),U.style.display="none",F.appendChild(U)):e.contentSegments?.length?pv(F,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=N(),W&&R?.useCaret&&!A&&k){let Y=Fi(),ve=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ve[ve.length-1];if(we?.parentNode)we.parentNode.insertBefore(Y,we.nextSibling);else{let xe=F.lastElementChild;xe?xe.appendChild(Y):F.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=xg(e,c,"span");Y.classList.add("persona-timestamp-inline");let ve=F.lastElementChild;ve?ve.appendChild(Y):F.appendChild(Y)}if(E.length>0){let Y=uv(E,!A&&!!k,()=>{A&&U&&(U.style.display="")});Y?S.appendChild(Y):A&&U&&(U.style.display="")}let fe=sv(e);if(fe.length>0){let Y=fv(fe);Y&&S.appendChild(Y)}let pe=iv(e);if(pe.length>0){let Y=mv(pe);Y&&S.appendChild(Y)}let Ee=lv(e);if(Ee.length>0){let Y=gv(Ee);Y&&S.appendChild(Y)}let Fe=e.contentSegments?.length?null:dv(e.contextMentions);if(Fe&&S.appendChild(Fe),S.appendChild(F),u&&f==="below"&&e.createdAt){let Y=xg(e,c);Y.classList.add("persona-mt-1"),S.appendChild(Y)}let se=e.role==="assistant"?nv(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!($&&$.trim()),ve=w.placeholder==="skeleton",we=ve&&w.buffer==="line"&&Y;if(Y)we&&S.appendChild(Ga());else if(ve)S.appendChild(Ga());else{let xe=Lp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);xe&&S.appendChild(xe)}}if(se&&e.stopReason&&!e.streaming&&(k||(F.style.display="none"),S.appendChild(ov(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Pp(e,o,r);S.appendChild(Y)}if(!d||e.role==="system")return S;let Z=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),de=hv(p,e.role);return g==="right"||g==="left"&&e.role==="user"?Z.append(S,de):Z.append(de,S),S.classList.remove("persona-max-w-[85%]"),S.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z},vg=(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}):zr(e,t,n,o,r,a)};var $r=new Set,xv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),bv=(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
|
+
`):""},Cg=(e,t)=>{let n=$r.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=ne(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")},Rp=(e,t)=>{let n=e.reasoning,o=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(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&&$r.has(e.id),l=n.status!=="complete",p=bv(e,r.previewMaxLines??3),c=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");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=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),S=()=>{let pe=y("span","");return pe.setAttribute("data-tool-elapsed",h),pe.textContent=Gs(n),pe},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:Gs(n),createElapsedElement:S});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=y("span","persona-text-xs persona-text-persona-primary");k.textContent=Jf(n),d.appendChild(k);let M=r.loadingAnimation??"none",A=f.activeTextTemplate,w=f.completeTextTemplate,T=l?A:w,R=E instanceof HTMLElement,b=(pe,Ee)=>{u.textContent="";let Fe=Ks(pe,""),se=0;for(let be of Fe){let Z=be.styles.length>0?(()=>{let de=y("span",be.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return u.appendChild(de),de})():u;if(be.isDuration&&l)Z.appendChild(S());else{let de=be.isDuration?Gs(n):be.text;Ee?se=So(Z,de,se):Z.appendChild(document.createTextNode(de))}}};if(!R&&T)if(k.style.display="none",u.style.display="",l&&M!=="none"){let pe=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",`${pe}ms`),b(T,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}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)),b(T,!0))}else b(T,!1);else if(!R&&l&&M!=="none"){u.style.display="";let pe=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",`${pe}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||g;u.textContent="",So(u,Ee,0)}n.status==="complete"&&(u.style.display="none")}else R||(n.status==="complete"?u.style.display="none":u.style.display="");let W=null;if(a){W=y("div","persona-flex persona-items-center");let Ee=ne(s?"chevron-up":"chevron-down",16,"currentColor",2);Ee?W.appendChild(Ee):W.textContent=s?"Hide":"Show";let Fe=y("div","persona-flex persona-items-center persona-ml-auto");Fe.append(W),c.append(d,Fe)}else c.append(d);let F=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","reasoning"),F.style.display="none",F.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let pe=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});xv(F,pe)||(F.textContent=p),F.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(c,F),o;let $=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=s?"":"none";let N=n.chunks.join(""),U=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(U),(()=>{if(c.setAttribute("aria-expanded",s?"true":"false"),W){W.innerHTML="";let Ee=ne(s?"chevron-up":"chevron-down",16,"currentColor",2);Ee?W.appendChild(Ee):W.textContent=s?"Hide":"Show"}$.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(c,F,$),o};var jr=new Set,vv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Cv=(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=yo(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
45
|
+
`):""},Ip=(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)"},wv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=Cv(e,o?.previewMaxLines??3),s=n?Qf(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=od(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=od(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},wg=(e,t,n)=>{let o=jr.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=ne(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")},Bp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(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&&jr.has(e.id),{summary:p,previewText:c,isActive:d}=wv(e,t),u=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");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=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),S=()=>{let N=y("span","");return N.setAttribute("data-tool-elapsed",h),N.textContent=Ia(n),N},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:Ia(n),createElapsedElement:S});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,A=o.completeTextTemplate,w=d?M:A,T=E instanceof HTMLElement,R=(N,U)=>{f.textContent="";let fe=n.name?.trim()||"tool",pe=Ks(N,fe),Ee=0;for(let Fe of pe){let se=Fe.styles.length>0?(()=>{let be=y("span",Fe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(be),be})():f;if(Fe.isDuration&&d)se.appendChild(S());else{let be=Fe.isDuration?Ia(n):Fe.text;U?Ee=So(se,be,Ee):se.appendChild(document.createTextNode(be))}}};if(!T)if(d&&k!=="none"){let N=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",`${N}ms`),w&&R(w,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${N}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)),w)R(w,!0);else{let U=f.textContent||p;f.textContent="",So(f,U,0)}}else w&&R(w,!1);let b=null;if(s){b=y("div","persona-flex persona-items-center");let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ne(l?"chevron-up":"chevron-down",16,N,2);U?b.appendChild(U):b.textContent=l?"Hide":"Show";let fe=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");fe.append(b),u.append(g,fe)}else u.append(g);let W=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","tool"),W.style.display="none",W.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let N=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});vv(W,N)||(W.textContent=c),W.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,W),r;let F=y("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 N=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?N.style.color=o.contentTextColor:o.headerTextColor&&(N.style.color=o.headerTextColor),N.textContent=n.name,F.appendChild(N)}if(n.args!==void 0){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let fe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Ip(fe,o),fe.textContent=yo(n.args),N.append(U,fe),F.appendChild(N)}if(n.chunks&&n.chunks.length){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let fe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Ip(fe,o),fe.textContent=n.chunks.join(""),N.append(U,fe),F.appendChild(N)}if(n.status==="complete"&&n.result!==void 0){let N=y("div","persona-space-y-1"),U=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let fe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",Ip(fe,o),fe.textContent=yo(n.result),N.append(U,fe),F.appendChild(N)}if(n.status==="complete"&&typeof n.duration=="number"){let N=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(N.style.color=o.contentTextColor),N.textContent=`Duration: ${n.duration}ms`,F.appendChild(N)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),b){b.innerHTML="";let N=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ne(l?"chevron-up":"chevron-down",16,N,2);U?b.appendChild(U):b.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",W.style.display=l?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(u,W,F),r};var lr=new Map,Ki=e=>{let n=(e.startsWith(Tn)?e.slice(Tn.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)},Ag=e=>e?.approval!==!1?e?.approval:void 0,Sg=(e,t)=>{let n=Ag(t)?.detailsDisplay??"collapsed";return lr.get(e)??n==="expanded"},Mg=(e,t,n)=>{let o=Ag(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=ne(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Tg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Sg(e,n);Mg(o,a,n),r.style.display=a?"":"none"};var Xi=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(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=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("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=ne(p,20,c,2);d&&l.appendChild(d);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",g.appendChild(f),!r){let b=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");b.setAttribute("data-approval-status",n.status),n.status==="approved"?(b.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",b.style.color="var(--persona-palette-colors-success-700, #15803d)",b.textContent="Approved"):n.status==="denied"?(b.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",b.style.color="var(--persona-palette-colors-error-700, #b91c1c)",b.textContent="Denied"):n.status==="timeout"&&(b.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",b.style.color="var(--persona-palette-colors-warning-700, #b45309)",b.textContent="Timeout"),g.appendChild(b)}u.appendChild(g);let S=n.toolType==="webmcp"||n.toolName.startsWith(Tn)?Ta(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...S?{displayTitle:S}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,M=E||(k?n.description:`The assistant wants to use \u201C${S??Ki(n.toolName)}\u201D.`),A=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=M,u.appendChild(A),n.reason){let b=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");b.setAttribute("data-approval-reason","true"),o?.reasonColor?b.style.color=o.reasonColor:o?.descriptionColor&&(b.style.color=o.descriptionColor);let W=y("span","persona-font-medium");W.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,b.appendChild(W),b.appendChild(document.createTextNode(n.reason)),u.appendChild(b)}let w=o?.detailsDisplay??"collapsed",T=!!n.description&&!k,R=T||!!n.parameters;if(w!=="hidden"&&R){let b=Sg(e.id,t),W=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(W.style.color=o.descriptionColor);let F=y("span");F.setAttribute("data-approval-details-label","true");let $=y("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),W.append(F,$),Mg(W,b,t),u.appendChild(W);let N=y("div");if(N.setAttribute("data-approval-details","true"),N.style.display=b?"":"none",T){let U=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,N.appendChild(U)}if(n.parameters){let U=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=yo(n.parameters),N.appendChild(U)}u.appendChild(N)}if(r){let b=y("div","persona-flex persona-gap-2 persona-mt-2");b.setAttribute("data-approval-buttons","true");let W=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",W.style.color=o?.approveButtonTextColor??"#ffffff",W.setAttribute("data-approval-action","approve");let F=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",W.appendChild(F));let $=document.createTextNode(o?.approveLabel??"Approve");W.appendChild($);let N=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");N.type="button",N.style.backgroundColor=o?.denyButtonColor??"transparent",N.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",N.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,N.setAttribute("data-approval-action","deny");let U=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",N.appendChild(U));let fe=document.createTextNode(o?.denyLabel??"Deny");N.appendChild(fe),b.append(W,N),u.appendChild(b)}return s.append(l,u),a.appendChild(s),a};function Av(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Eg(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??Av(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(),A=l?.()??null,w=A!=null?k.top+A:k.top,T=o==="top-start"||o==="top-end"?w-r-M.height:k.bottom+r,b=o==="bottom-end"||o==="top-end"?k.right-M.width:k.left,W=s?.()??null;if(W!=null){let F=Math.max(k.left,k.right-M.width);b=Math.min(Math.max(k.left+W,k.left),F)}n.style.top=`${T}px`,n.style.left=`${b}px`},S=()=>{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,A=()=>{if(!t.isConnected){S(),d?.("anchor-removed");return}h()},w=R=>{let b=typeof R.composedPath=="function"?R.composedPath():[];b.includes(n)||b.includes(t)||(S(),d?.("outside"))},T=k.setTimeout(()=>{M.addEventListener("pointerdown",w,!0)},0);k.addEventListener("scroll",A,!0),k.addEventListener("resize",A),f=()=>{k.clearTimeout(T),M.removeEventListener("pointerdown",w,!0),k.removeEventListener("scroll",A,!0),k.removeEventListener("resize",A)},c?.()};return{get isOpen(){return g},open:E,close:S,toggle:()=>g?S():E(),reposition:h,destroy:S}}function kg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Sv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Lg=(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))},dr=(e,t)=>{Lg(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)},Mv=e=>e?.approval!==!1?e?.approval:void 0,Tv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return lr.get(e)??n==="expanded"},Hp=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Ev=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Tn)?Ta(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??Ki(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},kv=e=>{let t=y("div","persona-approval-resolved"),n=ne("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=e.toolName?Ki(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Lv=(e,t,n,o,r,a,s)=>{let l=y("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&&Tv(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",S=y("button","persona-approval-head");S.type="button",u?(S.setAttribute("data-action","toggle-params"),S.setAttribute("aria-expanded",g?"true":"false"),S.setAttribute("aria-label",g?h:f)):S.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),k=ne("shield-check",16,"currentColor",2);k&&E.appendChild(k),S.appendChild(E);let M=Ev(n,o);if(u){let W=y("span","persona-approval-toggle");W.setAttribute("aria-hidden","true");let F=ne("chevron-down",14,"currentColor",2);F&&W.appendChild(F),M.append(" "),M.appendChild(W)}S.appendChild(M),l.appendChild(S);let A=y("div","persona-approval-body");if(u){let W=y("div","persona-approval-details");if(W.setAttribute("data-role","params"),W.hidden=!g,c){let F=y("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,W.appendChild(F)}if(d){let F=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=yo(n.parameters),W.appendChild(F)}A.appendChild(W)}if(n.reason){let W=y("p","persona-approval-reason");o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let F=y("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.append(F,document.createTextNode(n.reason)),A.appendChild(W)}let w=y("div","persona-approval-actions"),T=null,R=W=>{o?.approveButtonColor&&(W.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(W.style.color=o.approveButtonTextColor)},b=y("button","persona-approval-deny");if(b.type="button",b.setAttribute("data-action","deny"),o?.denyButtonColor&&(b.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(b.style.color=o.denyButtonTextColor),b.append(o?.denyLabel??"Deny"),s){let W=y("div","persona-approval-split"),F=y("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),R(F),F.append(o?.approveLabel??"Always allow",Hp("\u23CE"));let $=y("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),R($);let N=ne("chevron-down",15,"currentColor",2);N&&$.appendChild(N),W.append(F,$),w.append(W,b),b.append(Hp("Esc"));let U=y("div","persona-approval-menu"),fe=y("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",Hp("\u2318\u23CE")),U.appendChild(fe),T=Eg({anchor:W,content:U,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),fe.addEventListener("click",()=>{dr(e,t.id),r()})}else{let W=y("button","persona-approval-primary persona-approval-primary--solo");W.type="button",W.setAttribute("data-action","allow"),R(W),W.append(o?.approveLabel??"Allow"),w.append(W,b)}return A.appendChild(w),l.appendChild(A),l.addEventListener("click",W=>{let F=W.target instanceof Element?W.target.closest("[data-action]"):null;if(!F)return;let $=F.getAttribute("data-action");if($==="toggle-params"){let N=l.querySelector('[data-role="params"]');if(N){let U=N.hidden;N.hidden=!U,S.setAttribute("aria-expanded",U?"true":"false"),S.setAttribute("aria-label",U?h:f),lr.set(t.id,U)}return}if($==="toggle-menu"){T?.toggle();return}if($==="always"){dr(e,t.id),r({remember:!0});return}if($==="allow"){dr(e,t.id),r();return}if($==="deny"){dr(e,t.id),a();return}}),l},Pg=()=>{let e=Sv();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=Mv(s);if(l.status!=="pending"){if(dr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return kv(l)}Lg(e,o.id);let c=p?.enableAlwaysAllow===!0,d=Lv(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=>{kg(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),dr(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()])dr(e,o);e.latestPendingApprovalId=null}}};var Rg=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 S=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");S.type="button",S.textContent=h,S.disabled=g,p?.fontFamily&&(S.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(S.style.fontWeight=p.fontWeight),p?.paddingX&&(S.style.paddingLeft=p.paddingX,S.style.paddingRight=p.paddingX),p?.paddingY&&(S.style.paddingTop=p.paddingY,S.style.paddingBottom=p.paddingY),S.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(S),t.push(S)}),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 Ja=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 Qa=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 Pv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Rv=new Set(["step_start","execution_start"]),Iv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Bv=new Set(["step_complete","agent_turn_complete"]),Hv=new Set(["flow_complete","agent_complete"]),Ig=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,cr=(e,t)=>{let n=e[t];return Hg(n)?n:void 0};function Wp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ji(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Wv(e,t){return typeof t.type=="string"?t.type:e}function Dv(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 Fv(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 Bg(e){let t=cr(e,"result"),n=[cr(e,"tokens"),cr(e,"totalTokens"),t?cr(t,"tokens"):void 0,cr(e,"usage"),t?cr(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 Nv(e){let t=cr(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 Ov(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ya=class{constructor(t=Ov){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:Ji(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(!Hg(n)){Ig.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Wv(t,n),r=this.now();if(Pv.has(o)){this.startRun(r);return}if(Rv.has(o)){this.run||this.startRun(r);return}if(Iv.has(o)){if(!Fv(o,n))return;let a=Dv(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+Wp(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ji(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(Bv.has(o)){if(!this.run)return;let a=this.run,s=Bg(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Wp(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Ji(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Hv.has(o)){if(!this.run)return;let a=this.run,s=Bg(n),l=s??a.exactOutputTokens+Wp(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Ji(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(Ig.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:Nv(n)??o-t.startedAt}};function Gr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var _v={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)"}},Uv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},qv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Vv=100;function zv(e,t){let n={..._v,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Uv}function $v(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function jv(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 Gv(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 Kv(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 Xv(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 Jv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Qv(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 Yv(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=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Dp(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Gr(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=y("div",""),f=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);S&&h.appendChild(S);let E=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=o.timestampFormat??"relative";E.textContent=k==="relative"?$v(e.timestamp,n):jv(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=y("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 A=zv(e.type,o.badgeColors),w=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");w.style.backgroundColor=A.bg,w.style.color=A.text,w.style.borderColor=A.text+"50",w.textContent=e.type;let T=o.descriptionFields??qv,R=Gv(e.payload,T),b=null;R&&(b=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),b.textContent=R);let W=y("div","persona-flex-1 persona-min-w-0"),F=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=ne("clipboard","12px","currentColor",1.5);return $&&F.appendChild($),F.addEventListener("click",async N=>{N.stopPropagation(),await Kv(Xv(e)),F.innerHTML="";let U=ne("check","12px","currentColor",1.5);U&&F.appendChild(U),setTimeout(()=>{F.innerHTML="";let fe=ne("clipboard","12px","currentColor",1.5);fe&&F.appendChild(fe)},1500)}),f.appendChild(h),f.appendChild(E),M&&f.appendChild(M),f.appendChild(w),b&&f.appendChild(b),f.appendChild(W),f.appendChild(F),g.appendChild(f),p&&g.appendChild(Yv(e,s,l)),g}}function Wg(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,S=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Gr(S,h?.panel);let E=[],k="",M="",A=null,w=[],T={},R=0,b=Ii(),W=0,F=0,$=!1,N=null,U=!1,fe=0,pe=new Set,Ee=new Map,Fe="",se="",be=null,Z,de,Y,ve,we=null,xe=null,He=null;function Oe(){let _=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Gr(j,h?.headerBar),s){xe=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),xe.style.cursor="help",we=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),we.textContent="-- tok/s",He=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),He.style.display="none",He.style.pointerEvents="none";let Ye=xe,Ro=He,Io=()=>{if(!Ro.textContent)return;let is=Ye.getBoundingClientRect(),en=_.getBoundingClientRect();Ro.style.left=`${is.left-en.left}px`,Ro.style.top=`${is.bottom-en.top+4}px`,Ro.style.display="block"},ll=()=>{Ro.style.display="none"};xe.addEventListener("mouseenter",Io),xe.addEventListener("mouseleave",ll),xe.appendChild(we)}let ae=y("div","persona-flex-1");Z=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let nt=y("option","");nt.value="",nt.textContent="All events (0)",Z.appendChild(nt),de=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),de.type="button",de.title="Copy All";let dt=ne("clipboard-copy","12px","currentColor",1.5);dt&&de.appendChild(dt);let G=y("span","persona-event-copy-all persona-text-xs");G.textContent="Copy All",de.appendChild(G),xe&&j.appendChild(xe),j.appendChild(ae),j.appendChild(Z),j.appendChild(de);let Ve=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Gr(Ve,h?.searchBar);let Pe=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),Re=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Pe&&Re.appendChild(Pe),Y=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Gr(Y,h?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",ve=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let Te=ne("x","12px","currentColor",2);return Te&&ve.appendChild(Te),Ve.appendChild(Re),Ve.appendChild(Y),Ve.appendChild(ve),_.appendChild(j),_.appendChild(Ve),He&&_.appendChild(He),_}let Xe,qe=a.find(_=>_.renderEventStreamToolbar);qe?.renderEventStreamToolbar&&r?Xe=qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{k=j,Le(),he()},onSearchChange:j=>{M=j,Le(),he()}})??Oe():Xe=Oe();let ke=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");ke.style.display="none";function Ie(){if(!s||!we||!xe)return;let _=s(),j=Jv(_);we.textContent=j;let ae=Qv(_);He&&(He.textContent=ae,ae||(He.style.display="none")),xe.setAttribute("aria-label",ae?`Throughput: ${j}, ${ae}`:`Throughput: ${j}`)}let it=y("div","persona-flex-1 persona-min-h-0 persona-relative"),_e=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");_e.style.height="100%";let Qe=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Gr(Qe,h?.scrollIndicator),Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let fn=ne(c,"14px","currentColor",2);fn&&Qe.appendChild(fn);let Lt=y("span","");Lt.textContent=d,Qe.appendChild(Lt);let mt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");mt.style.display="none",it.appendChild(_e),it.appendChild(mt),it.appendChild(Qe),S.setAttribute("tabindex","0"),S.appendChild(Xe),S.appendChild(ke),S.appendChild(it);function Me(){let _=t.getAll(),j={};for(let Ve of _)j[Ve.type]=(j[Ve.type]||0)+1;let ae=Object.keys(j).sort(),nt=ae.length!==w.length||!ae.every((Ve,Pe)=>Ve===w[Pe]),Se=!nt&&ae.some(Ve=>j[Ve]!==T[Ve]),dt=_.length!==Object.values(T).reduce((Ve,Pe)=>Ve+Pe,0);if(!nt&&!Se&&!dt||(w=ae,T=j,!Z))return;let G=Z.value;if(Z.options[0].textContent=`All events (${_.length})`,nt){for(;Z.options.length>1;)Z.remove(1);for(let Ve of ae){let Pe=y("option","");Pe.value=Ve,Pe.textContent=`${Ve} (${j[Ve]||0})`,Z.appendChild(Pe)}G&&ae.includes(G)?Z.value=G:G&&(Z.value="",k="")}else for(let Ve=1;Ve<Z.options.length;Ve++){let Pe=Z.options[Ve];Pe.textContent=`${Pe.value} (${j[Pe.value]||0})`}}function me(){let _=t.getAll();if(k&&(_=_.filter(j=>j.type===k)),M){let j=M.toLowerCase();_=_.filter(ae=>ae.type.toLowerCase().includes(j)||ae.payload.toLowerCase().includes(j))}return _}function lt(){return k!==""||M!==""}function Le(){R=0,W=0,b.resume(),Qe.style.display="none"}function ue(_){pe.has(_)?pe.delete(_):pe.add(_),be=_;let j=_e.scrollTop,ae=b.isFollowing();U=!0,b.pause(),he(),_e.scrollTop=j,ae&&b.resume(),U=!1}function ie(){return ko(_e,50)}function he(){F=Date.now(),$=!1,Ie(),Me();let _=t.getEvictedCount();_>0?(ke.textContent=`${_.toLocaleString()} older events truncated`,ke.style.display=""):ke.style.display="none",E=me();let j=E.length,ae=t.getSize()>0;j===0&&ae&<()?(mt.textContent=M?`No events matching '${M}'`:"No events matching filter",mt.style.display="",_e.style.display="none"):(mt.style.display="none",_e.style.display=""),de&&(de.title=lt()?`Copy Filtered (${j})`:"Copy All"),p&&!b.isFollowing()&&j>R&&(W+=j-R,Lt.textContent=d?`${d}${W>0?` (${W})`:""}`:"",Qe.style.display=""),R=j;let nt=t.getAll(),Se=nt.length>0?nt[0].timestamp:0,dt=new Set(E.map(Pe=>Pe.id));for(let Pe of pe)dt.has(Pe)||pe.delete(Pe);let G=k!==Fe||M!==se,Ve=Ee.size===0&&E.length>0;if(G||Ve||E.length===0){_e.innerHTML="",Ee.clear();let Pe=document.createDocumentFragment();for(let Re=0;Re<E.length;Re++){let Te=Dp(E[Re],Re,Se,u,pe,ue,a,r);Ee.set(E[Re].id,Te),Pe.appendChild(Te)}_e.appendChild(Pe),Fe=k,se=M,be=null}else{if(be!==null){let Re=Ee.get(be);if(Re&&Re.parentNode===_e){let Te=E.findIndex(Ye=>Ye.id===be);if(Te>=0){let Ye=Dp(E[Te],Te,Se,u,pe,ue,a,r);_e.insertBefore(Ye,Re),Re.remove(),Ee.set(be,Ye)}}be=null}let Pe=new Set(E.map(Re=>Re.id));for(let[Re,Te]of Ee)Pe.has(Re)||(Te.remove(),Ee.delete(Re));for(let Re=0;Re<E.length;Re++){let Te=E[Re];if(!Ee.has(Te.id)){let Ye=Dp(Te,Re,Se,u,pe,ue,a,r);Ee.set(Te.id,Ye),_e.appendChild(Ye)}}}b.isFollowing()&&(_e.scrollTop=_e.scrollHeight)}function bt(){if(Date.now()-F>=Vv){N!==null&&(cancelAnimationFrame(N),N=null),he();return}$||($=!0,N=requestAnimationFrame(()=>{N=null,he()}))}let q=(_,j)=>{if(!de)return;de.innerHTML="";let ae=ne(_,"12px","currentColor",1.5);ae&&de.appendChild(ae);let nt=y("span","persona-text-xs");nt.textContent="Copy All",de.appendChild(nt),setTimeout(()=>{de.innerHTML="";let Se=ne("clipboard-copy","12px","currentColor",1.5);Se&&de.appendChild(Se);let dt=y("span","persona-text-xs");dt.textContent="Copy All",de.appendChild(dt),de.disabled=!1},j)},te=async()=>{if(de){de.disabled=!0;try{let _;lt()?_=E:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let j=_.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),q("check",1500)}catch{q("x",1500)}}},We=()=>{Z&&(k=Z.value,Le(),he())},Ae=()=>{!Y||!ve||(ve.style.display=Y.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=Y.value,Le(),he()},150))},I=()=>{!Y||!ve||(Y.value="",M="",ve.style.display="none",A&&clearTimeout(A),Le(),he())},J=()=>{if(U)return;let _=_e.scrollTop,{action:j,nextLastScrollTop:ae}=Bi({following:b.isFollowing(),currentScrollTop:_,lastScrollTop:fe,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=ae,j==="resume"?(b.resume(),W=0,Qe.style.display="none"):j==="pause"&&(b.pause(),p&&(Lt.textContent=d,Qe.style.display=""))},C=_=>{let j=Hi({following:b.isFollowing(),deltaY:_.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});j==="pause"?(b.pause(),p&&(Lt.textContent=d,Qe.style.display="")):j==="resume"&&(b.resume(),W=0,Qe.style.display="none")},P=()=>{p&&(_e.scrollTop=_e.scrollHeight,b.resume(),W=0,Qe.style.display="none")},B=_=>{let j=_.target;if(!j||j.closest("button"))return;let ae=j.closest("[data-event-id]");if(!ae)return;let nt=ae.getAttribute("data-event-id");nt&&ue(nt)},O=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Y?.focus(),Y?.select();return}_.key==="Escape"&&(Y&&document.activeElement===Y?(I(),Y.blur(),S.focus()):o&&o())};de&&de.addEventListener("click",te),Z&&Z.addEventListener("change",We),Y&&Y.addEventListener("input",Ae),ve&&ve.addEventListener("click",I),_e.addEventListener("scroll",J),_e.addEventListener("wheel",C,{passive:!0}),_e.addEventListener("click",B),Qe.addEventListener("click",P),S.addEventListener("keydown",O);function X(){A&&clearTimeout(A),N!==null&&(cancelAnimationFrame(N),N=null),$=!1,Ee.clear(),de&&de.removeEventListener("click",te),Z&&Z.removeEventListener("change",We),Y&&Y.removeEventListener("input",Ae),ve&&ve.removeEventListener("click",I),_e.removeEventListener("scroll",J),_e.removeEventListener("wheel",C),_e.removeEventListener("click",B),Qe.removeEventListener("click",P),S.removeEventListener("keydown",O)}return{element:S,update:bt,destroy:X}}}function Dg(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 S=h===g;f.setAttribute("aria-selected",S?"true":"false"),f.tabIndex=S||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 Fg(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=q=>({start:q===!1?!1:typeof q=="object"&&q?q.start!==!1:!0,end:q===!1?!1:typeof q=="object"&&q?q.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),g=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),U?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let S=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");S.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&S.classList.add("persona-artifact-toolbar-document");let E=y("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=a;let k=kt({icon:"x",label:s});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",A=Or({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:q=>{M=q==="source"?"source":"rendered",ie()}}),w=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,R=n?.documentToolbarShowCopyChevron===!0,b=n?.documentToolbarCopyMenuItems,W=!!(R&&b&&b.length>0),F=null,$,N=null,U=null;if(r&&(T||R)&&!W){if($=T?Jn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let q=ne("chevron-down",14,"currentColor",2);q&&$.appendChild(q)}}else r&&W?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=T?Jn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N=kt({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($,N)):r?$=kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=kt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let fe=r?kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):kt({icon:"refresh-cw",label:"Refresh"}),pe=r?kt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):kt({icon:"x",label:s}),Ee=kt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let Fe=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],be=()=>{let q=ke.find(I=>I.id===Ie)??ke[ke.length-1],te=q?.id??null,We=q?.artifactType==="markdown"?q.markdown??"":"",Ae=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:We,jsonPayload:Ae,id:te}},Z=async()=>{let q=ke.find(te=>te.id===Ie)??ke[ke.length-1];try{await navigator.clipboard.writeText(Va(q))}catch{}};if($.addEventListener("click",async()=>{let q=n?.onDocumentToolbarCopyMenuSelect;if(q&&W){let{markdown:te,jsonPayload:We,id:Ae}=be();try{await q({actionId:"primary",artifactId:Ae,markdown:te,jsonPayload:We})}catch{}return}await Z()}),N&&b?.length){let q=()=>h.closest("[data-persona-root]")??document.body,te=()=>{U=To({items:b.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:Ae,jsonPayload:I,id:J}=be(),C=n?.onDocumentToolbarCopyMenuSelect;try{C?await C({actionId:We,artifactId:J,markdown:Ae,jsonPayload:I}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(Ae):We==="json"||We==="source"?await navigator.clipboard.writeText(I):await navigator.clipboard.writeText(Ae||I)}catch{}},anchor:F??N,position:"bottom-right",portal:q()})};h.isConnected?te():requestAnimationFrame(te),N.addEventListener("click",We=>{We.stopPropagation(),U?.toggle()})}fe.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ie()}),pe.addEventListener("click",()=>{f(),t.onDismiss?.()});let de=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)S.replaceChildren(),F?w.append(F,fe,pe):w.append($,fe,pe),w.insertBefore(Fe,pe),w.insertBefore(Ee,pe),S.append(A.element,de,w);else{let q=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");q.append($,Fe,Ee,k),S.appendChild(E),S.appendChild(q)}l&&(S.style.paddingLeft=l,S.style.paddingRight=l);let Y=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=e.features?.artifacts?.renderTabBar,we=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),xe=Dg(Y,{onSelect:q=>t.onSelect(ke[q].id)}),He=q=>{let te=q.scrollWidth-q.clientWidth,We=te>1,Ae=Math.abs(q.scrollLeft);q.classList.toggle("persona-artifact-tab-fade-start",d&&We&&Ae>1),q.classList.toggle("persona-artifact-tab-fade-end",u&&We&&Ae<te-1)},Oe=0,Xe=()=>{if(Oe)return;let q=()=>{Oe=0,He(Y)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(q):setTimeout(q,0)};Y.addEventListener("scroll",()=>Xe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>He(Y)).observe(Y);let qe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let q of[Y,we])q.style.paddingLeft=l,q.style.paddingRight=l;qe.style.padding=l}h.appendChild(S),h.appendChild(Y),h.appendChild(we),h.appendChild(qe);let ke=[],Ie=null,it=!1,_e=!0,Qe=!1,fn=null,Lt="",mt=null,Me=!1,me=q=>q.artifactType==="markdown"&&!!q.file||r?M:"rendered",lt=q=>{r||(q&&!Me?(S.insertBefore(A.element,E),Me=!0):!q&&Me&&(A.element.remove(),Me=!1))},Le=()=>Ie&&ke.find(q=>q.id===Ie)||ke[ke.length-1],ue=()=>{let q=Ua(Le());if(!q){Fe.replaceChildren();return}let te=se.filter(We=>We.visible===void 0||We.visible(q)).map(We=>_r(We,{documentChrome:r,onClick:()=>{let Ae=Ua(Le());if(Ae)try{Promise.resolve(We.onClick(Ae)).catch(()=>{})}catch{}}}));Fe.replaceChildren(...te)},ie=()=>{ue();let q=r&&ke.length<=1,te=!!ve;if(Y.classList.toggle("persona-hidden",q||te),we.classList.toggle("persona-hidden",q||!te),te&&ve){let I=ke.map(J=>J.id).join("|")+" "+(Ie??"");if(I!==Lt){Lt=I;let J=ve({records:ke,selectedId:Ie,onSelect:t.onSelect});we.firstElementChild!==J&&we.replaceChildren(J)}}else{xe.beforeRender(),Y.replaceChildren();let I=[],J=-1;for(let[C,P]of ke.entries()){let B=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");B.type="button";let O=P.artifactType==="markdown"?P.file:void 0,X=O?Wn(O.path):P.title||P.id.slice(0,8),_=O?.path||P.title||X;B.textContent=X,B.title=_,B.setAttribute("aria-label",_),P.id===Ie&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=C),B.addEventListener("click",()=>t.onSelect(P.id)),Y.appendChild(B),I.push(B)}if(xe.render(I,J),J>=0&&Ie!==fn){fn=Ie;let C=I[J];typeof C.scrollIntoView=="function"&&C.scrollIntoView({block:"nearest",inline:"nearest"})}He(Y)}let We=Ie&&ke.find(I=>I.id===Ie)||ke[ke.length-1];if(!We){qe.replaceChildren(),mt=null,lt(!1);return}let Ae=We.artifactType==="markdown"?We.file:void 0;if(lt(!!Ae),r){let I=Ae?Ao(Ae):We.artifactType==="markdown"?"MD":We.component??"Component",J=(We.title||"Document").trim(),C=Ae?Wn(Ae.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${C} \xB7 ${I}`}else E.textContent=Ae?Wn(Ae.path):a;mt?(mt.el.parentElement!==qe&&qe.replaceChildren(mt.el),mt.update(We)):(mt=Pi(We,{config:e,resolveViewMode:me}),qe.replaceChildren(mt.el)),qe.classList.toggle("persona-artifact-content-flush",!!qe.querySelector(".persona-code-pre"))},he=()=>{let q=ke.length>0;if(h.classList.toggle("persona-hidden",!q),g){let Ae=((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;q&&Ae&&it?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},bt=()=>{Qe=!1,ie(),he()};return{element:h,backdrop:g,update(q){ke=q.artifacts,Ie=q.selectedId??q.artifacts[q.artifacts.length-1]?.id??null,ke.length>0&&(it=!0),Qe=!0,_e&&bt()},setMobileOpen(q){it=q,!q&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):he()},setExpanded(q){let te=ne(q?"minimize":"maximize",16,"currentColor",2);te&&Ee.replaceChildren(te);let We=q?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",We),Ee.title=We},setExpandToggleVisible(q){Ee.classList.toggle("persona-hidden",!q)},setCopyButtonVisible(q){r||$.classList.toggle("persona-hidden",!q)},setCustomActions(q){se=q,ue()},setTabFade(q){let te=c(q);te.start===d&&te.end===u||(d=te.start,u=te.end,He(Y))},setRenderTabBar(q){q!==ve&&(ve=q,Lt="",ie())},setVisible(q){q!==_e&&(_e=q,q&&Qe&&bt())}}}function Yt(e){return e?.features?.artifacts?.enabled===!0}function Ng(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"),!Yt(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 Zv(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 Og=["panel","seamless","detached"];function Fp(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Og.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Np(e){return!e||!Yt(e)?!1:Fp(e)==="detached"}function Za(e,t){if(!Yt(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"),Zv(e),Ng(e,t);return}let n=t.features?.artifacts?.layout,o=Fp(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"),Ng(e,t)}function es(e,t){for(let l of Og)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"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=Fp(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 _g(e,t){return!t||!Yt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function eC(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 tC(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 nC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function oC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Op(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 Ug(e,t,n,o,r,a){let s=eC(r,200),l=oC(t,n,o,200);l=Math.max(s,l);let p=tC(a);return p!==null&&(l=Math.min(l,p)),nC(e,s,l)}var qg={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"}},_p=(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=qg[s]??qg.init;a.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=y("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 S=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${s}-${h.name}`;let E=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,S.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),S.appendChild(M),d.appendChild(S)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),d.appendChild(u),a.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let S=n.formEndpoint??"/form",E=new FormData(d),k={};E.forEach((M,A)=>{k[A]=M}),k.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let A=await M.json();g.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Up=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()}},ts=new Up;var Vg=()=>{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 rC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},aC=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},ns=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rC(e),n=aC(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}},qp=e=>typeof e=="string"?e:e==null?"":String(e),pr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:qp(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=qp(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:qp(n.text)}}},zg=e=>Array.isArray(e)?e.map(t=>String(t)):[],os=e=>{let t=new Set(zg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(zg(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 sC=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}},iC=e=>e.map(t=>({...t,streaming:!1})),lC=e=>e.map(t=>({...t,status:"complete"})),Qi=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?iC(n.messages):void 0,artifacts:n.artifacts?lC(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 Kr=po(Os(),1);function dC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function cC(e,t){if(!dC(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 Yi(){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,Kr.parse)(n,Kr.STR|Kr.OBJ),a=cC(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function $g(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Zi(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=kn.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 jg(){let e=Yi();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Gg(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 rs(e){let t=Gg(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 el(e){let t=Gg(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 pC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function tl(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=pC}=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 S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,f.appendChild(S),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 R=1;R<=5;R++){let b=document.createElement("button");b.type="button",b.className="persona-feedback-rating-btn persona-feedback-star-btn",b.setAttribute("role","radio"),b.setAttribute("aria-checked","false"),b.setAttribute("aria-label",`${R} star${R>1?"s":""}: ${c[R-1]}`),b.title=c[R-1],b.dataset.rating=String(R),b.innerHTML=`
|
|
32
46
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
33
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>
|
|
34
48
|
</svg>
|
|
35
|
-
`,M.addEventListener("click",()=>{m=S,T.forEach((W,I)=>{let R=I<S;W.classList.toggle("selected",R),W.setAttribute("aria-checked",I===S-1?"true":"false")})}),T.push(M),E.appendChild(M)}g.appendChild(E);let A=null;if(c){let S=document.createElement("div");S.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"),S.appendChild(A),g.appendChild(S)}let k=document.createElement("div");k.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{r==null||r(),p.remove()});let C=document.createElement("button");return C.type="button",C.className="persona-feedback-btn persona-feedback-btn-submit",C.textContent=s,C.addEventListener("click",async()=>{if(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}C.disabled=!0,C.textContent="Submitting...";try{let S=(A==null?void 0:A.value.trim())||void 0;await t(m,S),p.remove()}catch(S){C.disabled=!1,C.textContent=s,console.error("[CSAT Feedback] Failed to submit:",S)}}),k.appendChild(w),k.appendChild(C),g.appendChild(k),p.appendChild(g),p}function yl(e){let{onSubmit:t,onDismiss:r,title:o="How likely are you to recommend us?",subtitle:n="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,lowLabel:d="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,h.appendChild(y);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=n,h.appendChild(E),u.appendChild(h);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=d;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,A.appendChild(k),A.appendChild(w);let C=document.createElement("div");C.className="persona-feedback-numbers";let S=[];for(let D=0;D<=10;D++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${D} out of 10`),O.textContent=String(D),O.dataset.rating=String(D),D<=6?O.classList.add("persona-feedback-detractor"):D<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{g=D,S.forEach((Q,me)=>{Q.classList.toggle("selected",me===D),Q.setAttribute("aria-checked",me===D?"true":"false")})}),S.push(O),C.appendChild(O)}T.appendChild(A),T.appendChild(C),u.appendChild(T);let M=null;if(c){let D=document.createElement("div");D.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"),D.appendChild(M),u.appendChild(D)}let W=document.createElement("div");W.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{r==null||r(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=s,R.addEventListener("click",async()=>{if(g===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let D=(M==null?void 0:M.value.trim())||void 0;await t(g,D),m.remove()}catch(D){R.disabled=!1,R.textContent=s,console.error("[NPS Feedback] Failed to submit:",D)}}),W.appendChild(I),W.appendChild(R),u.appendChild(W),m.appendChild(u),m}var es="persona-chat-history",Q0=30*1e3,J0={"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 Y0(e){var o,n,a;if(!e)return[];let t=[],r=Array.from((o=e.items)!=null?o:[]);for(let s of r){if(s.kind!=="file"||!s.type.startsWith("image/"))continue;let i=s.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let c=(n=J0[i.type])!=null?n:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${c}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let s of Array.from((a=e.files)!=null?a:[]))s.type.startsWith("image/")&&t.push(s);return t}function bl(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 Z0(e){var t,r,o,n,a,s,i,c,d;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(r=e.keyPrefix)!=null?r:"persona-",persist:{openState:(n=(o=e.persist)==null?void 0:o.openState)!=null?n:!0,voiceState:(s=(a=e.persist)==null?void 0:a.voiceState)!=null?s:!0,focusInput:(c=(i=e.persist)==null?void 0:i.focusInput)!=null?c:!0},clearOnChatClear:(d=e.clearOnChatClear)!=null?d:!0}:null}function ew(e){try{let t=e==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Ip=e=>!e||typeof e!="object"?{}:{...e},jx=e=>e.map(t=>({...t,streaming:!1})),Gx=(e,t,r)=>{let o=e!=null&&e.markdown?aa(e.markdown):null,n=Ha(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&n&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{var p,m,g;let s=(p=a.text)!=null?p:"",i=(m=a.message.rawContent)!=null?m:null;if(t){let u=t.process({text:s,raw:i!=null?i:s,message:a.message,streaming:a.streaming});u!==null&&(s=u.text,u.persist||(a.message.__skipPersist=!0),u.resubmit&&!a.streaming&&r&&r())}let c=na()!==null,d;if(e!=null&&e.postprocessMessage){let u=e.postprocessMessage({...a,text:s,raw:(g=i!=null?i:a.text)!=null?g:""});d=n?n(u):u}else if(o){let u=a.streaming?Jg(s):s,h=o(u);d=n&&c?n(h):h}else d=Fo(s);return d}};function Kx(e){var i,c,d,p;let t=v("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let r=(i=e==null?void 0:e.iconName)!=null?i:"upload",o=(c=e==null?void 0:e.iconSize)!=null?c:"48px",n=(d=e==null?void 0:e.iconColor)!=null?d:"rgba(59, 130, 246, 0.6)",a=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,s=he(r,o,n,a);if(s&&t.appendChild(s),e!=null&&e.label){let m=v("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var vl=(e,t,r)=>{var Bu,Du,Fu,Nu,Ou,_u,Uu,qu,Vu,zu,$u,ju,Gu,Ku,Xu,Qu,Ju,Yu,Zu,ef,tf,rf,of,nf,af,sf,lf,df,cf,pf,uf,ff,mf,gf,hf,xf,yf,bf,vf,wf,Cf,Sf,Af,Mf,Tf,Ef,kf,Lf,Pf,Rf;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=Oi(t),n=Vs.getForInstance(o.plugins),{plugin:a,teardown:s}=Tx();o.components&&an.registerAll(o.components);let i=Ux(),d=o.persistState===!1?null:(Bu=o.storageAdapter)!=null?Bu:fl(),p={},m=null,g=!1,u=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:x,open:b}=f;return b&&(g=!0),x}return f}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(d!=null&&d.load)try{let l=d.load();if(l&&typeof l.then=="function")m=l.then(f=>{let x=f!=null?f:{messages:[],metadata:{}};return u(x)});else{let f=l!=null?l:{messages:[],metadata:{}},x=u(f);x.metadata&&(p=Ip(x.metadata)),(Du=x.messages)!=null&&Du.length&&(o={...o,initialMessages:x.messages}),(Fu=x.artifacts)!=null&&Fu.length&&(o={...o,initialArtifacts:x.artifacts,initialSelectedArtifactId:(Nu=x.selectedArtifactId)!=null?Nu:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=u({messages:[],metadata:{}});(Ou=l.messages)!=null&&Ou.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>p,y=l=>{var x;p=(x=l({...p}))!=null?x:{},Ho()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],T=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick],A=$s({parsers:E,handlers:T,getSessionMetadata:h,updateSessionMetadata:y,emit:i.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let k=(Uu=(_u=o.launcher)==null?void 0:_u.enabled)!=null?Uu:!0,w=(Vu=(qu=o.launcher)==null?void 0:qu.autoExpand)!=null?Vu:!1,C=(zu=o.autoFocusInput)!=null?zu:!1,S=w,M=k,W=(ju=($u=o.layout)==null?void 0:$u.header)==null?void 0:ju.layout,I=!1,R=()=>On(o),D=()=>k||R(),O=R()?!1:k?w:!0,Q=!1,me=null,ue=()=>{Q=!0,me&&clearTimeout(me),me=setTimeout(()=>{Q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Q=!1)},1e4)},Z=Gx(o,A,ue),Le=(Ku=(Gu=o.features)==null?void 0:Gu.showReasoning)!=null?Ku:!0,He=(Qu=(Xu=o.features)==null?void 0:Xu.showToolCalls)!=null?Qu:!0,ie=(Yu=(Ju=o.features)==null?void 0:Ju.showEventStreamToggle)!=null?Yu:!1,Me=(ef=(Zu=o.features)==null?void 0:Zu.scrollToBottom)!=null?ef:{},oe=(rf=(tf=o.features)==null?void 0:tf.scrollBehavior)!=null?rf:{},ge=`${(nf=typeof o.persistState=="object"?(of=o.persistState)==null?void 0:of.keyPrefix:void 0)!=null?nf:"persona-"}event-stream`,Te=ie?new Us(ge):null,qe=(lf=(sf=(af=o.features)==null?void 0:af.eventStream)==null?void 0:sf.maxEvents)!=null?lf:2e3,j=ie?new _s(qe,Te):null,ee=ie?new qs:null,Ee=null,te=!1,le=null,ke=0;Te==null||Te.open().then(()=>j==null?void 0:j.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let nt={onCopy:l=>{var f,x;i.emit("message:copy",l),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(l.id,"copy").catch(b=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(x=(f=o.messageActions)==null?void 0:f.onCopy)==null||x.call(f,l)},onFeedback:l=>{var f,x;i.emit("message:feedback",l),q!=null&&q.isClientTokenMode()&&q.submitMessageFeedback(l.messageId,l.type).catch(b=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(x=(f=o.messageActions)==null?void 0:f.onFeedback)==null||x.call(f,l)}},yt=(df=o.statusIndicator)!=null?df:{},Kt=l=>{var f,x,b,P,B,V;return l==="idle"?(f=yt.idleText)!=null?f:rr.idle:l==="connecting"?(x=yt.connectingText)!=null?x:rr.connecting:l==="connected"?(b=yt.connectedText)!=null?b:rr.connected:l==="error"?(P=yt.errorText)!=null?P:rr.error:l==="paused"?(B=yt.pausedText)!=null?B:rr.paused:l==="resuming"?(V=yt.resumingText)!=null?V:rr.resuming:rr[l]};function jt(l,f,x,b){if(b==="idle"&&x.idleLink){l.textContent="";let P=document.createElement("a");P.href=x.idleLink,P.target="_blank",P.rel="noopener noreferrer",P.textContent=f,P.style.color="inherit",P.style.textDecoration="none",l.appendChild(P)}else l.textContent=f}let ct=fx({config:o,showClose:D()}),{wrapper:fe,panel:X,pillRoot:st}=ct.shell,je=ct.panelElements,{container:Ce,body:ve,messagesWrapper:Ye,suggestions:Vt,textarea:xe,sendButton:de,sendButtonWrapper:Ar,composerForm:Ct,statusText:br,introTitle:wo,introSubtitle:Co,closeButton:Ve,iconHolder:H,headerTitle:ce,headerSubtitle:Se,header:Ae,footer:Ie,actionsRow:et,leftActions:Qe,rightActions:gt}=je,pe=je.setSendButtonMode,N=je.micButton,ye=je.micButtonWrapper,ae=je.attachmentButton,mt=je.attachmentButtonWrapper,Ke=je.attachmentInput,Lt=je.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),ve.classList.add("persona-relative");let Et=12,bt=()=>{var l;return(l=Me.label)!=null?l:""},It=()=>{var l;return(l=Me.iconName)!=null?l:"arrow-down"},Qt=()=>Me.enabled!==!1,Ft=()=>{var l;return(l=oe.mode)!=null?l:"anchor-top"},er=()=>Ft()==="follow"||Ft()==="anchor-top"&&hn,So=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},Uo=()=>{var l;return(l=oe.restorePosition)!=null?l:"bottom"},io=()=>oe.pauseOnInteraction===!0,lo=()=>oe.showActivityWhilePinned!==!1,sn=()=>oe.announce===!0,zt=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");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let co=v("span","persona-flex persona-items-center"),qo=v("span",""),Fr=v("span","");Fr.setAttribute("data-persona-scroll-to-bottom-count",""),Fr.style.display="none",zt.append(co,qo,Fr),Ce.appendChild(zt);let Wr=v("div","persona-stream-anchor-spacer");Wr.setAttribute("aria-hidden","true"),Wr.setAttribute("data-persona-anchor-spacer",""),Wr.style.flexShrink="0",Wr.style.pointerEvents="none",Wr.style.height="0px",ve.appendChild(Wr);let Nr=v("div","persona-sr-only");Nr.setAttribute("aria-live","polite"),Nr.setAttribute("aria-atomic","true"),Nr.setAttribute("role","status"),Nr.setAttribute("data-persona-live-region",""),Object.assign(Nr.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"}),Ce.appendChild(Nr);let po=null,Ao=null,ln=l=>{!sn()||!l||(Ao=l,po===null&&(po=setTimeout(()=>{po=null,Ao&&sn()&&(Nr.textContent=Ao),Ao=null},400)))},Qr=()=>{let f=Ie.style.display==="none"?0:Ie.offsetHeight;zt.style.bottom=`${f+Et}px`};Qr();let dn=()=>{let l=!!bt();zt.setAttribute("aria-label",bt()||"Jump to latest"),zt.title=bt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),co.innerHTML="";let f=he(It(),"14px","currentColor",2);f?(co.appendChild(f),co.style.display=""):co.style.display="none",qo.textContent=bt(),qo.style.display=l?"":"none"};dn();let St=null,Mo=null,To=n.find(l=>l.renderHeader);if(To!=null&&To.renderHeader){let l=To.renderHeader({config:o,defaultRenderer:()=>{let f=nn({config:o,showClose:D()});return fa(Ce,f,o),f.header},onClose:()=>Ot(!1,"user")});if(l){let f=Ce.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),Ae=l,ct.header.element=l)}}let Vo=()=>{var f,x,b,P;if(!j)return;if(te=!0,!Ee&&j&&(Ee=Rx({buffer:j,getFullHistory:()=>j.getAllFromStore(),onClose:()=>uo(),config:o,plugins:n,getThroughput:()=>{var B;return(B=ee==null?void 0:ee.getMetric())!=null?B:{status:"idle"}}})),Ee&&(ve.style.display="none",(f=Ie.parentNode)==null||f.insertBefore(Ee.element,Ie),Ee.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Ir.actionIconColor}`;let B=(P=(b=(x=o.features)==null?void 0:x.eventStream)==null?void 0:b.classNames)==null?void 0:P.toggleButtonActive;B&&B.split(/\s+/).forEach(V=>V&&ht.classList.add(V))}let l=()=>{if(!te)return;let B=Date.now();B-ke>=200&&(Ee==null||Ee.update(),ke=B),le=requestAnimationFrame(l)};ke=0,le=requestAnimationFrame(l),qr(),i.emit("eventStream:opened",{timestamp:Date.now()})},uo=()=>{var l,f,x;if(te){if(te=!1,Ee&&Ee.element.remove(),ve.style.display="",ht){ht.style.boxShadow="";let b=(x=(f=(l=o.features)==null?void 0:l.eventStream)==null?void 0:f.classNames)==null?void 0:x.toggleButtonActive;b&&b.split(/\s+/).forEach(P=>P&&ht.classList.remove(P))}le!==null&&(cancelAnimationFrame(le),le=null),qr(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(ie){let l=(pf=(cf=o.features)==null?void 0:cf.eventStream)==null?void 0:pf.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=v("button",f),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ir.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let x=he("activity","18px","currentColor",1.5);x&&ht.appendChild(x);let b=je.clearChatButtonWrapper,P=je.closeButtonWrapper,B=b||P;B&&B.parentNode===Ae?Ae.insertBefore(ht,B):Ae.appendChild(ht),ht.addEventListener("click",()=>{te?uo():Vo()})}let Un=l=>{var P,B,V,U,_;let f=o.attachments;if(!(f!=null&&f.enabled))return;let x=(P=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?P:l.querySelector(".persona-attachment-previews");if(!x){x=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),x.setAttribute("data-persona-composer-attachment-previews",""),x.style.display="none";let ne=l.querySelector("[data-persona-composer-form]");ne!=null&&ne.parentNode?ne.parentNode.insertBefore(x,ne):l.insertBefore(x,l.firstChild)}if(!((B=l.querySelector("[data-persona-composer-attachment-input]"))!=null?B:l.querySelector('input[type="file"]'))){let ne=v("input");ne.type="file",ne.setAttribute("data-persona-composer-attachment-input",""),ne.accept=((V=f.allowedTypes)!=null?V:on).join(","),ne.multiple=((U=f.maxFiles)!=null?U:4)>1,ne.style.display="none",ne.setAttribute("aria-label",(_=f.buttonTooltipText)!=null?_:"Attach files"),l.appendChild(ne)}},Eo=n.find(l=>l.renderComposer);if(Eo!=null&&Eo.renderComposer){let l=o.composer,f=Eo.renderComposer({config:o,defaultRenderer:()=>Ka({config:o}).footer,onSubmit:x=>{var V;if(!q||q.isStreaming())return;let b=x.trim(),P=(V=St==null?void 0:St.hasAttachments())!=null?V:!1;if(!b&&!P)return;cu();let B;P&&(B=[],B.push(...St.getContentParts()),b&&B.push(Es(b))),q.sendMessage(b,{contentParts:B}),P&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:((uf=o.voiceRecognition)==null?void 0:uf.enabled)===!0?()=>{Mo==null||Mo()}:void 0});f&&(ct.replaceComposer(f),Ie=ct.composer.footer)}let qn=l=>{let f=(...re)=>{for(let J of re){let be=l.querySelector(J);if(be)return be}return null},x=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),P=l.querySelector("[data-persona-composer-submit]"),B=l.querySelector("[data-persona-composer-mic]"),V=l.querySelector("[data-persona-composer-status]");x&&(Ct=x),b&&(xe=b),P&&(de=P),B&&(N=B,ye=B.parentElement),V&&(br=V);let U=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Vt=U);let _=f("[data-persona-composer-attachment-button]",".persona-attachment-button");_&&(ae=_,mt=_.parentElement),Ke=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ne=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ne&&(et=ne)};Un(Ie),qn(Ie);let Hr=(xf=(ff=o.layout)==null?void 0:ff.contentMaxWidth)!=null?xf:R()?(hf=(gf=(mf=o.launcher)==null?void 0:mf.composerBar)==null?void 0:gf.contentMaxWidth)!=null?hf:"720px":void 0;if(Hr&&(Ye.style.maxWidth=Hr,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),Hr&&Ct&&!R()&&(Ct.style.maxWidth=Hr,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Hr&&Vt&&!R()&&(Vt.style.maxWidth=Hr,Vt.style.marginLeft="auto",Vt.style.marginRight="auto"),Hr&&Lt&&!R()&&(Lt.style.maxWidth=Hr,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(yf=o.attachments)!=null&&yf.enabled&&Ke&&Lt){St=pa.fromConfig(o.attachments),St.setPreviewsContainer(Lt),Ke.addEventListener("change",x=>{let b=x.target;St==null||St.handleFileSelect(b.files),b.value=""});let l=o.attachments.dropOverlay,f=Kx(l);Ce.appendChild(f)}(()=>{var b,P;let l=(P=(b=o.layout)==null?void 0:b.slots)!=null?P:{},f=B=>{switch(B){case"body-top":return Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return Vt;case"composer":return Ct;case"footer-bottom":return br;default:return null}},x=(B,V)=>{var U;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Ae.insertBefore(V,Ae.firstChild);else if(B==="header-right")Ae.appendChild(V);else{let _=Ae.querySelector(".persona-flex-col");_?(U=_.parentNode)==null||U.insertBefore(V,_.nextSibling):Ae.appendChild(V)}break;case"body-top":{let _=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(V):ve.insertBefore(V,ve.firstChild);break}case"body-bottom":ve.appendChild(V);break;case"footer-top":Vt.replaceWith(V);break;case"footer-bottom":br.replaceWith(V);break;default:break}};for(let[B,V]of Object.entries(l))if(V)try{let U=V({config:o,defaultContent:()=>f(B)});U&&x(B,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,U)}})();let cn=l=>{var V,U;let x=l.target.closest('button[data-expand-header="true"]');if(!x)return;let b=x.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let P=b.getAttribute("data-message-id");if(!P)return;let B=x.getAttribute("data-bubble-type");if(B==="reasoning")Qa.has(P)?Qa.delete(P):Qa.add(P),xx(P,b);else if(B==="tool")Ja.has(P)?Ja.delete(P):Ja.add(P),yx(P,b,o);else if(B==="approval"){let _=o.approval!==!1?o.approval:void 0,ne=((V=_==null?void 0:_.detailsDisplay)!=null?V:"collapsed")==="expanded",re=(U=ga.get(P))!=null?U:ne;ga.set(P,!re),Cx(P,b,o)}Ro.delete(P)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Ye.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cn(l))}),Ye.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let x=Ye.getRootNode(),b=typeof x.getSelection=="function"?x.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let P=b.toString(),B=Xh(P);!B||B===P||(f.setData("text/plain",B),l.preventDefault())});let zo=new Map,pn=null,un="idle",Vn={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},zn=(l,f)=>{let{icon:x,label:b}=Vn[f];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let P=he(x,14,"currentColor",2);P&&(l.innerHTML="",l.appendChild(P))},fn=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{var B;let x=f.closest("[data-actions-for]"),b=(B=x==null?void 0:x.getAttribute("data-actions-for"))!=null?B:null;zn(f,b&&b===pn?un:"idle")})};Ye.addEventListener("click",l=>{var V;let x=l.target.closest(".persona-message-action-btn[data-action]");if(!x)return;l.preventDefault(),l.stopPropagation();let b=x.closest("[data-actions-for]");if(!b)return;let P=b.getAttribute("data-actions-for");if(!P)return;let B=x.getAttribute("data-action");if(B==="copy"){let _=q.getMessages().find(ne=>ne.id===P);if(_&&nt.onCopy){let ne=_.content||"";navigator.clipboard.writeText(ne).then(()=>{x.classList.add("persona-message-action-success");let re=he("check",14,"currentColor",2);re&&(x.innerHTML="",x.appendChild(re)),setTimeout(()=>{x.classList.remove("persona-message-action-success");let J=he("copy",14,"currentColor",2);J&&(x.innerHTML="",x.appendChild(J))},2e3)}).catch(re=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",re)}),nt.onCopy(_)}}else if(B==="read-aloud")q.toggleReadAloud(P);else if(B==="upvote"||B==="downvote"){let _=((V=zo.get(P))!=null?V:null)===B,ne=B==="upvote"?"thumbs-up":"thumbs-down";if(_){zo.delete(P),x.classList.remove("persona-message-action-active");let re=he(ne,14,"currentColor",2);re&&(x.innerHTML="",x.appendChild(re))}else{let re=B==="upvote"?"downvote":"upvote",J=b.querySelector(`[data-action="${re}"]`);if(J){J.classList.remove("persona-message-action-active");let ze=he(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(J.innerHTML="",J.appendChild(ze))}zo.set(P,B),x.classList.add("persona-message-action-active");let be=he(ne,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),x.innerHTML="",x.appendChild(be)),x.classList.remove("persona-message-action-pop"),x.offsetWidth,x.classList.add("persona-message-action-pop");let Ne=q.getMessages().find(Ue=>Ue.id===P);Ne&&nt.onFeedback&&nt.onFeedback({type:B,messageId:Ne.id,message:Ne})}}}),Ye.addEventListener("click",l=>{let x=l.target.closest("button[data-approval-action]");if(!x)return;l.preventDefault(),l.stopPropagation();let b=x.closest(".persona-approval-bubble");if(!b)return;let P=b.getAttribute("data-message-id");if(!P)return;let B=x.getAttribute("data-approval-action");if(!B)return;let V=B==="approve"?"approved":"denied",_=q.getMessages().find(re=>re.id===P);if(!(_!=null&&_.approval))return;let ne=b.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(J=>{J.disabled=!0,J.style.opacity="0.5",J.style.cursor="not-allowed"}),_.approval.toolType==="webmcp"?q.resolveWebMcpApproval(P,V):q.resolveApproval(_.approval,V)});let vt=null,Or=null,_r={artifacts:[],selectedId:null},Mr=!1,At={current:null};Ye.addEventListener("click",l=>{var J,be,Fe,Ne,Ue;let x=l.target.closest("[data-download-artifact]");if(!x)return;l.preventDefault(),l.stopPropagation();let b=x.getAttribute("data-download-artifact");if(!b||((Fe=(be=(J=o.features)==null?void 0:J.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Fe.call(be,{type:"download",artifactId:b}))===!0)return;let B=q.getArtifactById(b),V=B==null?void 0:B.markdown,U=(B==null?void 0:B.title)||"artifact";if(!V){let ze=x.closest("[data-open-artifact]"),ut=ze==null?void 0:ze.closest("[data-message-id]"),ot=ut==null?void 0:ut.getAttribute("data-message-id");if(ot){let Pe=q.getMessages().find($e=>$e.id===ot);if(Pe!=null&&Pe.rawContent)try{let $e=JSON.parse(Pe.rawContent);V=(Ne=$e==null?void 0:$e.props)==null?void 0:Ne.markdown,U=((Ue=$e==null?void 0:$e.props)==null?void 0:Ue.title)||U}catch{}}}if(!V)return;let _=new Blob([V],{type:"text/markdown"}),ne=URL.createObjectURL(_),re=document.createElement("a");re.href=ne,re.download=`${U}.md`,re.click(),URL.revokeObjectURL(ne)}),Ye.addEventListener("click",l=>{var B,V,U;let x=l.target.closest("[data-open-artifact]");if(!x)return;let b=x.getAttribute("data-open-artifact");!b||((U=(V=(B=o.features)==null?void 0:B.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:U.call(V,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Mr=!1,q.selectArtifact(b),ko())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;f.hasAttribute("data-open-artifact")&&(l.preventDefault(),f.click())});let Jr=je.composerOverlay,Yr=(l,f,x)=>{var U,_,ne,re;let b=f.trim();if(!b||!At.current)return;let P=(U=l.getAttribute("data-tool-call-id"))!=null?U:"",B=x.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:P,answer:b,answers:x.structured,values:(_=x.values)!=null?_:x.source==="multi"?b.split(", "):[b],isFreeText:B,source:x.source},bubbles:!0,composed:!0})),Ln(Jr,P);let V=At.current.getMessages().find(J=>{var be;return((be=J.toolCall)==null?void 0:be.id)===P});(ne=V==null?void 0:V.agentMetadata)!=null&&ne.awaitingLocalTool?At.current.resolveAskUserQuestion(V,(re=x.structured)!=null?re:b):At.current.sendMessage(b)},Ur=l=>{var P;let f=At.current;if(!f)return;let x=(P=l.getAttribute("data-tool-call-id"))!=null?P:"",b=f.getMessages().find(B=>{var V;return((V=B.toolCall)==null?void 0:V.id)===x});b&&f.persistAskUserQuestionProgress(b,{answers:ci(l,b),currentIndex:ao(l)})},mn=l=>Object.entries(l).map(([f,x])=>`${f}: ${Array.isArray(x)?x.join(", "):x}`).join(" | "),we=l=>{var P,B,V;if(((B=(P=o.features)==null?void 0:P.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let f=ao(l),x=Fa(l);if(f>=x-1)return;let b=(V=At.current)==null?void 0:V.getMessages().find(U=>{var _;return((_=U.toolCall)==null?void 0:_.id)===l.getAttribute("data-tool-call-id")});b&&(pi(l,b,o,f+1),Ur(l))};Jr.addEventListener("click",l=>{var B,V,U,_,ne,re,J,be,Fe,Ne,Ue,ze,ut,ot;let x=l.target.closest("[data-ask-user-action]");if(!x)return;let b=x.closest("[data-persona-ask-sheet-for]");if(!b)return;let P=x.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),P==="dismiss"){let We=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ln(Jr,We);let Pe=(V=At.current)==null?void 0:V.getMessages().find($e=>{var Xe;return((Xe=$e.toolCall)==null?void 0:Xe.id)===We});(U=Pe==null?void 0:Pe.agentMetadata)!=null&&U.awaitingLocalTool&&((_=At.current)==null||_.markAskUserQuestionResolved(Pe),(ne=At.current)==null||ne.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(P==="pick"){let We=x.getAttribute("data-option-label");if(!We)return;let Pe=b.getAttribute("data-multi-select")==="true",$e=kn(b);if($e&&Pe){let Xe=sa(b)[ao(b)],xt=new Set(Array.isArray(Xe)?Xe:[]);xt.has(We)?xt.delete(We):xt.add(We),Pn(b,Array.from(xt)),Ur(b);return}if($e){Pn(b,We),Ur(b),we(b);return}if(Pe){let Xe=x.getAttribute("aria-pressed")==="true";x.setAttribute("aria-pressed",Xe?"false":"true"),x.classList.toggle("persona-ask-pill-selected",!Xe);let xt=b.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=Xl(b).length===0);return}Yr(b,We,{source:"pick",values:[We]});return}if(P==="submit-multi"){let We=Xl(b);if(We.length===0)return;Yr(b,We.join(", "),{source:"multi",values:We});return}if(P==="open-free-text"){let We=b.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Pe=We.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(P==="focus-free-text"){let We=b.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(P==="submit-free-text"){let We=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(re=We==null?void 0:We.value)!=null?re:"";if(!Pe.trim())return;if(kn(b)){Pn(b,Pe.trim()),Ur(b),we(b);return}Yr(b,Pe,{source:"free-text"});return}if(P==="next"||P==="back"){if(!At.current)return;let We=(J=b.getAttribute("data-tool-call-id"))!=null?J:"",Pe=At.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===We});if(!Pe)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),Xe=(Fe=(be=$e==null?void 0:$e.value)==null?void 0:be.trim())!=null?Fe:"";if(Xe){let Be=sa(b)[ao(b)];(typeof Be!="string"||Be!==Xe)&&Pn(b,Xe)}let xt=P==="next"?1:-1,F=ao(b)+xt;pi(b,Pe,o,F),Ur(b);return}if(P==="submit-all"){if(!At.current)return;let We=(Ne=b.getAttribute("data-tool-call-id"))!=null?Ne:"",Pe=At.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===We});if(!Pe)return;let $e=b.querySelector('[data-ask-free-text-input="true"]'),Xe=(ze=(Ue=$e==null?void 0:$e.value)==null?void 0:Ue.trim())!=null?ze:"";Xe&&Pn(b,Xe);let xt=ci(b,Pe);At.current.persistAskUserQuestionProgress(Pe,{answers:xt,currentIndex:ao(b)});let F=mn(xt);Yr(b,F||"(submitted)",{source:"submit-all",structured:xt});return}if(P==="skip"){if(!At.current)return;let We=(ut=b.getAttribute("data-tool-call-id"))!=null?ut:"",Pe=At.current.getMessages().find(Re=>{var Je;return((Je=Re.toolCall)==null?void 0:Je.id)===We});if(!Pe)return;let $e=kn(b),Xe=ao(b),xt=Fa(b),F=Xe>=xt-1;if(!$e){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Ln(Jr,We),(ot=Pe.agentMetadata)!=null&&ot.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Pe),At.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}Pn(b,"");let Be=b.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),F){let Re=ci(b,Pe),Je=mn(Re);Yr(b,Je||"(skipped)",{source:"submit-all",structured:Re});return}pi(b,Pe,o,Xe+1),Ur(b);return}}),Jr.addEventListener("keydown",l=>{var B;if(l.key!=="Enter")return;let x=l.target;if(!((B=x.matches)!=null&&B.call(x,'[data-ask-free-text-input="true"]')))return;let b=x.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let P=x.value;if(P.trim()){if(kn(b)){Pn(b,P.trim()),Ur(b),we(b);return}Yr(b,P,{source:"free-text"})}});let $o=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if((f==null?void 0:f.tagName)==="INPUT"||(f==null?void 0:f.tagName)==="TEXTAREA"||f!=null&&f.isContentEditable)return;let x=Jr.querySelector("[data-persona-ask-sheet-for]");if(!x||x.getAttribute("data-ask-layout")!=="rows"||x.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),B=x.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];B&&(l.preventDefault(),B.click())};document.addEventListener("keydown",$o);let Zr=null,Nt=null,eo=null,jo=null,rs=()=>{};function va(){jo==null||jo(),jo=null}let os=()=>{var V;if(!Zr||!Nt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),x=((V=e.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||x){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let b=Zr.firstElementChild;if(!b||b===Nt)return;let P=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${P}px`,Nt.style.zIndex="5";let B=b.offsetWidth-P/2;Nt.style.left=`${Math.max(0,B)}px`},$n=()=>{},ko=()=>{var x,b,P,B,V;if(!vt||!so(o))return;pl(e,o),ul(e,o),$n();let l=(B=(P=(b=(x=o.features)==null?void 0:x.artifacts)==null?void 0:b.layout)==null?void 0:P.narrowHostMaxWidth)!=null?B:520,f=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l),vt.update(_r),Mr?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(V=vt.backdrop)==null||V.classList.add("persona-hidden")):_r.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),rs()};if(so(o)){X.style.position="relative";let l=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Ce),vt=Hx(o,{onSelect:x=>{var b;return(b=At.current)==null?void 0:b.selectArtifact(x)},onDismiss:()=>{Mr=!0,ko()}}),vt.element.classList.add("persona-hidden"),Zr=f,f.appendChild(l),f.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(f),rs=()=>{var b,P,B,V;if(!Zr||!vt)return;if(!(((B=(P=(b=o.features)==null?void 0:b.artifacts)==null?void 0:P.layout)==null?void 0:B.resizable)===!0)){eo==null||eo(),eo=null,va(),Nt&&(Nt.remove(),Nt=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Nt){let U=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let _=e.ownerDocument,ne=(V=_.defaultView)!=null?V:window,re=J=>{var ut,ot;if(!vt||J.button!==0||e.classList.contains("persona-artifact-narrow-host")||ne.innerWidth<=640)return;J.preventDefault(),va();let be=J.clientX,Fe=vt.element.getBoundingClientRect().width,Ne=(ot=(ut=o.features)==null?void 0:ut.artifacts)==null?void 0:ot.layout,Ue=We=>{let Pe=Zr.getBoundingClientRect().width,$e=e.classList.contains("persona-artifact-appearance-seamless"),Xe=$e?0:Nx(Zr,ne),xt=$e?0:U.getBoundingClientRect().width||6,F=Fe-(We.clientX-be),Be=Ox(F,Pe,Xe,xt,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);vt.element.style.width=`${Be}px`,vt.element.style.maxWidth="none",os()},ze=()=>{_.removeEventListener("pointermove",Ue),_.removeEventListener("pointerup",ze),_.removeEventListener("pointercancel",ze),jo=null;try{U.releasePointerCapture(J.pointerId)}catch{}};jo=ze,_.addEventListener("pointermove",Ue),_.addEventListener("pointerup",ze),_.addEventListener("pointercancel",ze);try{U.setPointerCapture(J.pointerId)}catch{}};U.addEventListener("pointerdown",re),Nt=U,Zr.insertBefore(U,vt.element),eo=()=>{U.removeEventListener("pointerdown",re)}}if(Nt){let U=_r.artifacts.length>0&&!Mr;Nt.classList.toggle("persona-hidden",!U),os()}},$n=()=>{var ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,We,Pe,$e,Xe;if(!k||!vt||((re=(ne=o.launcher)==null?void 0:ne.sidebarMode)!=null?re:!1)||or(o)&&Kr(o).reveal==="emerge")return;let b=(J=e.ownerDocument.defaultView)!=null?J:window,P=(Fe=(be=o.launcher)==null?void 0:be.mobileFullscreen)!=null?Fe:!0,B=(Ue=(Ne=o.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?Ue:640;if(P&&b.innerWidth<=B||!Fx(o,k))return;let V=(ot=(ut=(ze=o.launcher)==null?void 0:ze.width)!=null?ut:o.launcherWidth)!=null?ot:Gr,U=(Xe=($e=(Pe=(We=o.features)==null?void 0:We.artifacts)==null?void 0:Pe.layout)==null?void 0:$e.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";_r.artifacts.length>0&&!Mr?(X.style.width=U,X.style.maxWidth=U):(X.style.width=V,X.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(Or=new ResizeObserver(()=>{ko()}),Or.observe(X))}else X.appendChild(Ce),R()&&st&&(je.peekBanner&&st.appendChild(je.peekBanner),st.appendChild(Ie));e.appendChild(fe),st&&e.appendChild(st);let gn=()=>{var Be,Re,Je,Pt,Oe,Gt,wt,lr,Br,Ht,hr,Vr,Ge,Rt,zr,Qn,Jn,Yn,Zn,Pa,Ra,Xt,ea,Sn,An,Zo,ta,Ze;if(R()){X.style.width="100%",X.style.maxWidth="100%";let Dt=(Re=(Be=o.launcher)==null?void 0:Be.composerBar)!=null?Re:{},Bt=fe.dataset.state==="expanded",$t=(Je=Dt.expandedSize)!=null?Je:"anchored";if(!(Bt&&$t!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let ft=(Oe=(Pt=o.theme)==null?void 0:Pt.components)==null?void 0:Oe.panel,Ut=$a(o),xr=(mr,no)=>{var Mn;return mr==null||mr===""?no:(Mn=Va(Ut,mr))!=null?Mn:mr},$r="1px solid var(--persona-border)",Do="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",fr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=xr(ft==null?void 0:ft.border,$r),Ce.style.borderRadius=xr(ft==null?void 0:ft.borderRadius,fr),Ce.style.boxShadow=xr(ft==null?void 0:ft.shadow,Do),Ce.style.overflow="hidden";return}let l=or(o),f=(wt=(Gt=o.launcher)==null?void 0:Gt.sidebarMode)!=null?wt:!1,x=l||f||((Br=(lr=o.launcher)==null?void 0:lr.fullHeight)!=null?Br:!1),b=((Ht=o.launcher)==null?void 0:Ht.enabled)===!1,P=(Vr=(hr=o.theme)==null?void 0:hr.components)==null?void 0:Vr.panel,B=$a(o),V=(Dt,Bt)=>{var $t;return Dt==null||Dt===""?Bt:($t=Va(B,Dt))!=null?$t:Dt},U=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,_=(zr=(Rt=o.launcher)==null?void 0:Rt.mobileFullscreen)!=null?zr:!0,ne=(Jn=(Qn=o.launcher)==null?void 0:Qn.mobileBreakpoint)!=null?Jn:640,re=U.innerWidth<=ne,J=_&&re&&k,be=(Zn=(Yn=o.launcher)==null?void 0:Yn.position)!=null?Zn:"bottom-left",Fe=be==="bottom-left"||be==="top-left",Ne=(Ra=(Pa=o.launcher)==null?void 0:Pa.zIndex)!=null?Ra:Sr,Ue=f||J?"none":"1px solid var(--persona-border)",ze=J?"none":f?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!J&&(ze="none",Ue="none");let ut=f||J?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=V(P==null?void 0:P.border,Ue),We=V(P==null?void 0:P.shadow,ze),Pe=V(P==null?void 0:P.borderRadius,ut),$e=ve.scrollTop;e.style.cssText="",fe.style.cssText="",X.style.cssText="",Ce.style.cssText="",ve.style.cssText="",Ie.style.cssText="",te&&(ve.style.display="none");let Xe=()=>{var Bt;if($e<=0)return;((Bt=ve.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(ve.scrollTop===$e)return;let $t=ve.scrollHeight-ve.clientHeight;$t<=0||(ve.scrollTop=Math.min($e,$t))})};if(J){fe.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"),fe.style.cssText=`
|
|
49
|
+
`,b.addEventListener("click",()=>{u=R,k.forEach((W,F)=>{let $=F<R;W.classList.toggle("selected",$),W.setAttribute("aria-checked",F===R-1?"true":"false")})}),k.push(b),E.appendChild(b)}g.appendChild(E);let M=null;if(p){let R=document.createElement("div");R.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"),R.appendChild(M),g.appendChild(R)}let A=document.createElement("div");A.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=l,w.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 R=M?.value.trim()||void 0;await t(u,R),d.remove()}catch(R){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",R)}}),A.appendChild(w),A.appendChild(T),g.appendChild(A),d.appendChild(g),d}function nl(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 S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,h.appendChild(S);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 A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=d,M.appendChild(A),M.appendChild(w);let T=document.createElement("div");T.className="persona-feedback-numbers";let R=[];for(let N=0;N<=10;N++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${N} out of 10`),U.textContent=String(N),U.dataset.rating=String(N),N<=6?U.classList.add("persona-feedback-detractor"):N<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{g=N,R.forEach((fe,pe)=>{fe.classList.toggle("selected",pe===N),fe.setAttribute("aria-checked",pe===N?"true":"false")})}),R.push(U),T.appendChild(U)}k.appendChild(M),k.appendChild(T),f.appendChild(k);let b=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",b=document.createElement("textarea"),b.className="persona-feedback-comment",b.placeholder=a,b.rows=3,b.setAttribute("aria-label","Additional comments"),N.appendChild(b),f.appendChild(N)}let W=document.createElement("div");W.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 $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=s,$.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let N=b?.value.trim()||void 0;await t(g,N),u.remove()}catch(N){$.disabled=!1,$.textContent=s,console.error("[NPS Feedback] Failed to submit:",N)}}),W.appendChild(F),W.appendChild($),f.appendChild(W),u.appendChild(f),u}var Xr="persona-chat-history",uC=30*1e3,fC=641,mC={"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 gC(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=mC[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 ol(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 hC(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 yC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Vp=e=>!e||typeof e!="object"?{}:{...e},Kg=e=>e.map(t=>({...t,streaming:!1})),Xg=(e,t,n)=>{let o=e?.markdown?Xo(e.markdown):null,r=Tr(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=zn()!==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?Ef(s):s,u=o(d);c=r&&p?r(u):u}else c=Bn(s);return c}};function Jg(e){let t=y("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=ne(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=y("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var xC=(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},bC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:xC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),rl=(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=xi(t),r=ts.getForInstance(o.plugins),{plugin:a,teardown:s}=Pg();o.components&&kn.registerAll(o.components);let l=Vg(),c=o.persistState===!1?null:o.storageAdapter??Qi(),d={},u=null,g=!1,f=i=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:x,open:v}=m;return v&&(g=!0),x}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")u=i.then(m=>f(m??{messages:[],metadata:{}}));else{let x=f(i??{messages:[],metadata:{}});x.metadata&&(d=Vp(x.metadata)),x.messages?.length&&(o={...o,initialMessages:x.messages}),x.artifacts?.length&&(o={...o,initialArtifacts:x.artifacts,initialSelectedArtifactId:x.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let h=()=>d,S=i=>{d=i({...d})??{},Sl()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ns],k=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[pr.message,pr.messageAndClick],M=os({parsers:E,handlers:k,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,T=o.autoFocusInput??!1,R=w,b=A,W=o.layout?.header?.layout,F=!1,$=()=>Po(o),N=()=>A||$(),U=$()?!1:A?w:!0,fe=!1,pe=null,Ee=()=>{fe=!0,pe&&clearTimeout(pe),pe=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},Fe=Xg(o,M,Ee),se=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,de=o.features?.scrollToBottom??{},Y=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,xe=Z?new Qa(we):null,He=o.features?.eventStream?.maxEvents??2e3,Oe=Z?new Ja(He,xe):null,Xe=Z?new Ya:null,qe=null,ke=!1,Ie=null,it=0;xe?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let _e={onCopy:i=>{l.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=>{l.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)}},Qe=o.statusIndicator??{},fn=i=>i==="idle"?Qe.idleText??Wt.idle:i==="connecting"?Qe.connectingText??Wt.connecting:i==="connected"?Qe.connectedText??Wt.connected:i==="error"?Qe.errorText??Wt.error:i==="paused"?Qe.pausedText??Wt.paused:i==="resuming"?Qe.resumingText??Wt.resuming:Wt[i];function Lt(i,m,x,v){if(v==="idle"&&x.idleLink){i.textContent="";let L=document.createElement("a");L.href=x.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 mt=gg({config:o,showClose:N()}),{wrapper:Me,panel:me,pillRoot:lt}=mt.shell,Le=mt.panelElements,{container:ue,body:ie,messagesWrapper:he,suggestions:bt,textarea:q,sendButton:te,sendButtonWrapper:We,composerForm:Ae,statusText:I,introTitle:J,introSubtitle:C,closeButton:P,iconHolder:B,headerTitle:O,headerSubtitle:X,header:_,footer:j,actionsRow:ae,rightActions:nt}=Le,Se=Le.leftActions,dt=Le.setSendButtonMode,G=Le.micButton,Ve=Le.micButtonWrapper,Pe=Le.attachmentButton,Re=Le.attachmentButtonWrapper,Te=Le.attachmentInput,Ye=Le.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ie.classList.add("persona-relative");let Ro=12,Io=()=>de.label??"",ll=()=>de.iconName??"arrow-down",is=()=>de.enabled!==!1,en=()=>Y.mode??"anchor-top",Yn=()=>en()==="follow"||en()==="anchor-top"&&aa,au=()=>Y.anchorTopOffset??16,Wh=()=>Y.restorePosition??"bottom",su=()=>Y.pauseOnInteraction===!0,iu=()=>Y.showActivityWhilePinned!==!1,lu=()=>Y.announce===!0,Bt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Bt.type="button",Bt.style.display="none",Bt.setAttribute("data-persona-scroll-to-bottom","true");let Qr=y("span","persona-flex persona-items-center"),dl=y("span",""),Bo=y("span","");Bo.setAttribute("data-persona-scroll-to-bottom-count",""),Bo.style.display="none",Bt.append(Qr,dl,Bo),ue.appendChild(Bt);let Zn=y("div","persona-stream-anchor-spacer");Zn.setAttribute("aria-hidden","true"),Zn.setAttribute("data-persona-anchor-spacer",""),Zn.style.flexShrink="0",Zn.style.pointerEvents="none",Zn.style.height="0px",ie.appendChild(Zn);let Ho=y("div","persona-sr-only");Ho.setAttribute("aria-live","polite"),Ho.setAttribute("aria-atomic","true"),Ho.setAttribute("role","status"),Ho.setAttribute("data-persona-live-region",""),Object.assign(Ho.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(Ho);let Yr=null,ls=null,du=i=>{!lu()||!i||(ls=i,Yr===null&&(Yr=setTimeout(()=>{Yr=null,ls&&lu()&&(Ho.textContent=ls),ls=null},400)))},ur=()=>{let m=j.style.display==="none"?0:j.offsetHeight;Bt.style.bottom=`${m+Ro}px`};ur();let cu=()=>{let i=!!Io();Bt.setAttribute("aria-label",Io()||"Jump to latest"),Bt.title=Io(),Bt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Qr.innerHTML="";let m=ne(ll(),"14px","currentColor",2);m?(Qr.appendChild(m),Qr.style.display=""):Qr.style.display="none",dl.textContent=Io(),dl.style.display=i?"":"none"};cu();let Tt=null,rn=null,pu=null,uu=r.find(i=>i.renderHeader);if(uu?.renderHeader){let i=uu.renderHeader({config:o,defaultRenderer:()=>{let m=Qn({config:o,showClose:N()});return sr(ue,m,o),m.header},onClose:()=>ht(!1,"user")});if(i){let m=ue.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),_=i,mt.header.element=i)}}let cl=()=>{if(!Oe)return;if(ke=!0,!qe&&Oe&&(qe=Wg({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Zr(),config:o,plugins:r,getThroughput:()=>Xe?.getMetric()??{status:"idle"}})),qe&&(ie.style.display="none",j.parentNode?.insertBefore(qe.element,j),qe.update()),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(x=>x&&at.classList.add(x))}let i=()=>{if(!ke)return;let m=Date.now();m-it>=200&&(qe?.update(),it=m),Ie=requestAnimationFrame(i)};it=0,Ie=requestAnimationFrame(i),sn(),l.emit("eventStream:opened",{timestamp:Date.now()})},Zr=()=>{if(ke){if(ke=!1,qe&&qe.element.remove(),ie.style.display="",at){at.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&at.classList.remove(m))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),sn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(Z){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:"");at=y("button",m),at.style.width="28px",at.style.height="28px",at.style.color=Qt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let x=ne("activity","18px","currentColor",1.5);x&&at.appendChild(x);let v=Le.clearChatButtonWrapper,L=Le.closeButtonWrapper,H=v||L;H&&H.parentNode===_?_.insertBefore(at,H):_.appendChild(at),at.addEventListener("click",()=>{ke?Zr():cl()})}let Dh=i=>{let m=o.attachments;if(!m?.enabled)return;let x=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!x){x=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),x.setAttribute("data-persona-composer-attachment-previews",""),x.style.display="none";let L=i.querySelector("[data-persona-composer-form]");L?.parentNode?L.parentNode.insertBefore(x,L):i.insertBefore(x,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let L=y("input");L.type="file",L.setAttribute("data-persona-composer-attachment-input",""),L.accept=(m.allowedTypes??Xn).join(","),L.multiple=(m.maxFiles??4)>1,L.style.display="none",L.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(L)}},fu=r.find(i=>i.renderComposer);if(fu?.renderComposer){let i=o.composer,m=fu.renderComposer({config:o,defaultRenderer:()=>Vr({config:o}).footer,onSubmit:x=>{if(!z||z.isStreaming())return;let v=x.trim(),L=Tt?.hasAttachments()??!1;if(!v&&!L)return;qu();let H;L&&(H=[],H.push(...Tt.getContentParts()),v&&H.push(bo(v))),z.sendMessage(v,{contentParts:H}),L&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Te?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{pu?.()}:void 0});m&&(mt.replaceComposer(m),j=mt.composer.footer)}let Fh=i=>{let m=(...le)=>{for(let re of le){let ye=i.querySelector(re);if(ye)return ye}return null},x=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),L=i.querySelector("[data-persona-composer-submit]"),H=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");x&&(Ae=x),v&&(q=v),L&&(te=L),H&&(G=H,Ve=H.parentElement),Q&&(I=Q);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(bt=V);let K=m("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(Pe=K,Re=K.parentElement),Te=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(ae=oe),Se=m(".persona-widget-composer__left-actions")};Dh(j),Fh(j);let eo=o.layout?.contentMaxWidth??($()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(eo&&(he.style.maxWidth=eo,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%"),eo&&Ae&&!$()&&(Ae.style.maxWidth=eo,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),eo&&bt&&!$()&&(bt.style.maxWidth=eo,bt.style.marginLeft="auto",bt.style.marginRight="auto"),eo&&Ye&&!$()&&(Ye.style.maxWidth=eo,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&Te&&Ye){Tt=nr.fromConfig(o.attachments),Tt.setPreviewsContainer(Ye),Te.addEventListener("change",x=>{let v=x.target;Tt?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=Jg(i);ue.appendChild(m)}let Nh=()=>rn?.prefetch();if(o.contextMentions?.enabled&&q&&(rn=Em({config:o,textarea:q,anchor:Ae??q,getMessages:()=>z.getMessages(),liveRegionHost:ue}),rn)){let i=q;i.parentElement?.insertBefore(rn.contextRow,i);let m=rn.affordanceButtons;for(let x=m.length-1;x>=0;x--){let v=m[x];Se?Se.insertBefore(v,Se.firstChild):Ae?.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 he;case"footer-top":return bt;case"composer":return Ae;case"footer-bottom":return I;default:return null}},x=(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 H=_.querySelector(".persona-flex-col");H?H.parentNode?.insertBefore(L,H.nextSibling):_.appendChild(L)}break;case"body-top":{let H=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(L):ie.insertBefore(L,ie.firstChild);break}case"body-bottom":ie.appendChild(L);break;case"footer-top":bt.replaceWith(L);break;case"footer-bottom":I.replaceWith(L);break;default:break}};for(let[v,L]of Object.entries(i))if(L)try{let H=L({config:o,defaultContent:()=>m(v)});H&&x(v,H)}catch(H){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,H)}})();let mu=i=>{let x=i.target.closest('button[data-expand-header="true"]');if(!x)return;let v=x.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let H=x.getAttribute("data-bubble-type");if(H==="reasoning")$r.has(L)?$r.delete(L):$r.add(L),Cg(L,v);else if(H==="tool")jr.has(L)?jr.delete(L):jr.add(L),wg(L,v,o);else if(H==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=lr.get(L)??V;lr.set(L,!K),Tg(L,v,o)}No.delete(L)};he.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),mu(i))}),he.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),mu(i))}),he.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let x=he.getRootNode(),v=typeof x.getSelection=="function"?x.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let L=v.toString(),H=Ym(L);!H||H===L||(m.setData("text/plain",H),i.preventDefault())});let pl=new Map,gu=null,hu="idle",Oh={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},_h=(i,m)=>{let{icon:x,label:v}=Oh[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=ne(x,14,"currentColor",2);L&&(i.innerHTML="",i.appendChild(L))},yu=()=>{he.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;_h(m,v&&v===gu?hu:"idle")})};he.addEventListener("click",i=>{let x=i.target.closest(".persona-message-action-btn[data-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.closest("[data-actions-for]");if(!v)return;let L=v.getAttribute("data-actions-for");if(!L)return;let H=x.getAttribute("data-action");if(H==="copy"){let V=z.getMessages().find(K=>K.id===L);if(V&&_e.onCopy){let K=V.content||"";navigator.clipboard.writeText(K).then(()=>{x.classList.add("persona-message-action-success");let oe=ne("check",14,"currentColor",2);oe&&(x.innerHTML="",x.appendChild(oe)),setTimeout(()=>{x.classList.remove("persona-message-action-success");let le=ne("copy",14,"currentColor",2);le&&(x.innerHTML="",x.appendChild(le))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),_e.onCopy(V)}}else if(H==="read-aloud")z.toggleReadAloud(L);else if(H==="upvote"||H==="downvote"){let V=(pl.get(L)??null)===H,K=H==="upvote"?"thumbs-up":"thumbs-down";if(V){pl.delete(L),x.classList.remove("persona-message-action-active");let oe=ne(K,14,"currentColor",2);oe&&(x.innerHTML="",x.appendChild(oe))}else{let oe=H==="upvote"?"downvote":"upvote",le=v.querySelector(`[data-action="${oe}"]`);if(le){le.classList.remove("persona-message-action-active");let st=ne(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);st&&(le.innerHTML="",le.appendChild(st))}pl.set(L,H),x.classList.add("persona-message-action-active");let re=ne(K,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),x.innerHTML="",x.appendChild(re)),x.classList.remove("persona-message-action-pop"),x.offsetWidth,x.classList.add("persona-message-action-pop");let Ge=z.getMessages().find(yt=>yt.id===L);Ge&&_e.onFeedback&&_e.onFeedback({type:H,messageId:Ge.id,message:Ge})}}}),he.addEventListener("click",i=>{let x=i.target.closest("button[data-approval-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.closest(".persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let H=x.getAttribute("data-approval-action");if(!H)return;let Q=H==="approve"?"approved":"denied",K=z.getMessages().find(le=>le.id===L);if(!K?.approval)return;let oe=v.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?z.resolveWebMcpApproval(L,Q):z.resolveApproval(K.approval,Q)});let Ze=null,ea=null,ta=()=>{},na="none",ds=null,bn={artifacts:[],selectedId:null},Nn=!1,vn=!1,oa=!1,fr=!1,xu=()=>fr||bn.artifacts.some(i=>Jo(o.features?.artifacts,i.artifactType)==="panel"),cs=()=>bn.artifacts.length>0&&!Nn&&xu(),gt={current:null},ul=(i,m)=>{let x=z.getArtifactById(m),v=x?.markdown,L=x?.title||"artifact",H=x?.file,Q=x?.artifactType??"markdown";if(!v){let oe=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let re=z.getMessages().find(ye=>ye.id===oe);if(re?.rawContent)try{let ye=JSON.parse(re.rawContent);v=ye?.props?.markdown,L=ye?.props?.title||L,ye?.props?.file&&typeof ye.props.file=="object"&&(H=ye.props.file),!x&&typeof ye?.props?.artifactType=="string"&&(Q=ye.props.artifactType)}catch{}}}return{markdown:v,title:L,file:H,artifactType:Q}};he.addEventListener("click",i=>{let x=i.target.closest("[data-download-artifact]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:H,title:Q,file:V}=ul(x,v);if(!H)return;let{filename:K,mime:oe,content:le}=Hm({title:Q,markdown:H,file:V}),re=new Blob([le],{type:oe}),ye=URL.createObjectURL(re),Ge=document.createElement("a");Ge.href=ye,Ge.download=K,Ge.click(),URL.revokeObjectURL(ye)}),he.addEventListener("click",i=>{let x=i.target.closest("[data-artifact-custom-action]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.getAttribute("data-artifact-custom-action");if(!v)return;let L=x.closest("[data-artifact-inline]"),H=L?null:x.closest("[data-open-artifact]"),Q=L?L.getAttribute("data-artifact-inline"):H?.getAttribute("data-open-artifact")??null,K=(L?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===v);if(!K)return;let{markdown:oe,title:le,file:re,artifactType:ye}=ul(x,Q??""),Ge={artifactId:Q,title:le,artifactType:ye,markdown:oe,file:re};try{Promise.resolve(K.onClick(Ge)).catch(()=>{})}catch{}}),he.addEventListener("click",i=>{let x=i.target.closest("[data-copy-artifact]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.getAttribute("data-copy-artifact");if(!v)return;let L=z.getArtifactById(v),H="";if(L)H=Va(L);else{let{markdown:Q,file:V,artifactType:K}=ul(x,v);K==="markdown"&&(H=Va({id:v,artifactType:"markdown",status:"complete",markdown:Q??"",...V?{file:V}:{}}))}H&&navigator.clipboard.writeText(H).then(()=>{let Q=ne("check",16,"currentColor",2);Q&&(x.replaceChildren(Q),setTimeout(()=>{let V=ne("copy",16,"currentColor",2);V&&x.replaceChildren(V)},1500))}).catch(()=>{})}),he.addEventListener("click",i=>{let x=i.target.closest("[data-expand-artifact-inline]");if(!x)return;i.preventDefault(),i.stopPropagation();let v=x.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Nn=!1,fr=!0,vn=!0,oa=!0,z.selectArtifact(v),On())}),he.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let x=m.closest("[data-open-artifact]");if(!x)return;let v=x.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),Nn=!1,fr=!0,z.selectArtifact(v),On())}),he.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 mr=Le.composerOverlay,gr=(i,m,x)=>{let v=m.trim();if(!v||!gt.current)return;let L=i.getAttribute("data-tool-call-id")??"",H=x.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:v,answers:x.structured,values:x.values??(x.source==="multi"?v.split(", "):[v]),isFreeText:H,source:x.source},bubbles:!0,composed:!0})),go(mr,L);let Q=gt.current.getMessages().find(V=>V.toolCall?.id===L);Q?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(Q,x.structured??v):gt.current.sendMessage(v)},Wo=i=>{let m=gt.current;if(!m)return;let x=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(L=>L.toolCall?.id===x);v&&m.persistAskUserQuestionProgress(v,{answers:Us(i,v),currentIndex:xn(i)})},bu=i=>Object.entries(i).map(([m,x])=>`${m}: ${Array.isArray(x)?x.join(", "):x}`).join(" | "),fl=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=xn(i),x=Lr(i);if(m>=x-1)return;let v=gt.current?.getMessages().find(L=>L.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(qs(i,v,o,m+1),Wo(i))};mr.addEventListener("click",i=>{let x=i.target.closest("[data-ask-user-action]");if(!x)return;let v=x.closest("[data-persona-ask-sheet-for]");if(!v)return;let L=x.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),L==="dismiss"){let H=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),go(mr,H);let Q=gt.current?.getMessages().find(V=>V.toolCall?.id===H);Q?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(Q),gt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(L==="pick"){let H=x.getAttribute("data-option-label");if(!H)return;let Q=v.getAttribute("data-multi-select")==="true",V=mo(v);if(V&&Q){let K=Qo(v)[xn(v)],oe=new Set(Array.isArray(K)?K:[]);oe.has(H)?oe.delete(H):oe.add(H),ho(v,Array.from(oe)),Wo(v);return}if(V){ho(v,H),Wo(v),fl(v);return}if(Q){let K=x.getAttribute("aria-pressed")==="true";x.setAttribute("aria-pressed",K?"false":"true"),x.classList.toggle("persona-ask-pill-selected",!K);let oe=v.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=Ql(v).length===0);return}gr(v,H,{source:"pick",values:[H]});return}if(L==="submit-multi"){let H=Ql(v);if(H.length===0)return;gr(v,H.join(", "),{source:"multi",values:H});return}if(L==="open-free-text"){let H=v.querySelector('[data-ask-free-text-row="true"]');H&&(H.classList.remove("persona-hidden"),H.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 Q=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(mo(v)){ho(v,Q.trim()),Wo(v),fl(v);return}gr(v,Q,{source:"free-text"});return}if(L==="next"||L==="back"){if(!gt.current)return;let H=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(re=>re.toolCall?.id===H);if(!Q)return;let K=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let re=Qo(v)[xn(v)];(typeof re!="string"||re!==K)&&ho(v,K)}let oe=L==="next"?1:-1,le=xn(v)+oe;qs(v,Q,o,le),Wo(v);return}if(L==="submit-all"){if(!gt.current)return;let H=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(re=>re.toolCall?.id===H);if(!Q)return;let K=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&ho(v,K);let oe=Us(v,Q);gt.current.persistAskUserQuestionProgress(Q,{answers:oe,currentIndex:xn(v)});let le=bu(oe);gr(v,le||"(submitted)",{source:"submit-all",structured:oe});return}if(L==="skip"){if(!gt.current)return;let H=v.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(ye=>ye.toolCall?.id===H);if(!Q)return;let V=mo(v),K=xn(v),oe=Lr(v),le=K>=oe-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),go(mr,H),Q.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(Q),gt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}ho(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),le){let ye=Us(v,Q),Ge=bu(ye);gr(v,Ge||"(skipped)",{source:"submit-all",structured:ye});return}qs(v,Q,o,K+1),Wo(v);return}}),mr.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let x=i.target;if(!x.matches?.('[data-ask-free-text-input="true"]'))return;let v=x.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let L=x.value;if(L.trim()){if(mo(v)){ho(v,L.trim()),Wo(v),fl(v);return}gr(v,L,{source:"free-text"})}});let vu=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 x=mr.querySelector("[data-persona-ask-sheet-for]");if(!x||x.getAttribute("data-ask-layout")!=="rows"||x.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),H=x.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];H&&(i.preventDefault(),H.click())};document.addEventListener("keydown",vu);let to=null,vt=null,ra=null,ps=null,ml=()=>{},Cu=!1,us="",fs="";function gl(){ps?.(),ps=null}let wu=()=>{if(!to||!vt)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,x=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||x){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let v=to.firstElementChild;if(!v||v===vt)return;let L=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${L}px`,vt.style.zIndex="5";let H=Op(to,m),Q=v.offsetWidth+H/2-L/2;vt.style.left=`${Math.max(0,Q)}px`},ms=()=>{},Uh=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>x?!1:A||It(o)},gs=()=>!Yt(o)||!cs()||e.classList.contains("persona-artifact-narrow-host")||Uh()||(e.ownerDocument.defaultView??window).innerWidth<fC?"none":Np(o)?"detached":"welded",On=()=>{if(!Ze||!Yt(o))return;Za(e,o),es(e,o),ms();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let x=cs();Ze.setVisible(x),Ze.update(bn),Nn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),vn=!1,oa=!1):bn.artifacts.length>0&&xu()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),vn=!1,oa=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(v),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!oa&&(vn=!1),vn!==Cu){let H=Ze.element;vn?(us=H.style.width,fs=H.style.maxWidth,H.style.removeProperty("width"),H.style.removeProperty("max-width")):(us&&(H.style.width=us),fs&&(H.style.maxWidth=fs),us="",fs=""),Cu=vn}e.classList.toggle("persona-artifact-expanded",vn),Ze.setExpanded(vn);let L=gs();L!==na&&(na=L,ta()),ml()};if(Yt(o)){me.style.position="relative";let i=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Ze=Fg(o,{onSelect:x=>gt.current?.selectArtifact(x),onDismiss:()=>{Nn=!0,On()},onToggleExpand:()=>{let x=!vn,v=bn.selectedId??bn.artifacts[bn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:x})!==!0&&(vn=x,x||(oa=!1),On())}}),Ze.element.classList.add("persona-hidden"),to=m,m.appendChild(i),m.appendChild(Ze.element),Ze.backdrop&&me.appendChild(Ze.backdrop),me.appendChild(m),ml=()=>{if(!to||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ra?.(),ra=null,gl(),vt&&(vt.remove(),vt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!vt){let v=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let L=e.ownerDocument,H=L.defaultView??window,Q=V=>{if(!Ze||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||H.innerWidth<=640)return;V.preventDefault(),gl();let K=V.clientX,oe=Ze.element.getBoundingClientRect().width,le=o.features?.artifacts?.layout,re=Ge=>{let yt=to.getBoundingClientRect().width,st=e.classList.contains("persona-artifact-welded-split"),jt=Op(to,H),Dt=st?0:v.getBoundingClientRect().width||6,D=oe-(Ge.clientX-K),Ne=Ug(D,yt,jt,Dt,le?.resizableMinWidth,le?.resizableMaxWidth);Ze.element.style.width=`${Ne}px`,Ze.element.style.maxWidth="none",wu()},ye=()=>{L.removeEventListener("pointermove",re),L.removeEventListener("pointerup",ye),L.removeEventListener("pointercancel",ye),ps=null;try{v.releasePointerCapture(V.pointerId)}catch{}};ps=ye,L.addEventListener("pointermove",re),L.addEventListener("pointerup",ye),L.addEventListener("pointercancel",ye);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",Q),vt=v,to.insertBefore(v,Ze.element),ra=()=>{v.removeEventListener("pointerdown",Q)}}if(vt){let v=cs();vt.classList.toggle("persona-hidden",!v),wu()}},ms=()=>{if(!A||!Ze||(o.launcher?.sidebarMode??!1)||It(o)&&on(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640;if(L&&v.innerWidth<=H||!_g(o,A))return;let Q=o.launcher?.width??o.launcherWidth??pn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";cs()?(me.style.width=V,me.style.maxWidth=V):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(ea=new ResizeObserver(()=>{On()}),ea.observe(me))}else me.appendChild(ue);$()&<&&(Le.peekBanner&<.appendChild(Le.peekBanner),lt.appendChild(j)),e.appendChild(Me),lt&&e.appendChild(lt);let hs=()=>{if($()){me.style.width="100%",me.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},tn=Me.dataset.state==="expanded",Ls=Rt.expandedSize??"anchored";if(!(tn&&Ls!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let xa=o.theme?.components?.panel,Ps=wo(o),Ar=(Vn,jo)=>Vn==null||Vn===""?jo:Jt(Ps,Vn)??Vn,ba="1px solid var(--persona-border)",_l="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",$o="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Ar(xa?.border,ba),ue.style.borderRadius=Ar(xa?.borderRadius,$o),ue.style.boxShadow=Ar(xa?.shadow,_l),ue.style.overflow="hidden";return}let i=It(o),m=o.launcher?.sidebarMode??!1,x=i||m||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,L=o.launcher?.detachedPanel===!0,H=o.theme?.components?.panel,Q=wo(o),V=(Rt,tn)=>Rt==null||Rt===""?tn:Jt(Q,Rt)??Rt,K=e.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,le=o.launcher?.mobileBreakpoint??640,re=K.innerWidth<=le,ye=oe&&re&&A,Ge=i&&oe&&re,yt=o.launcher?.position??"bottom-left",st=yt==="bottom-left"||yt==="top-left",jt=o.launcher?.zIndex??zt,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",D="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Ne="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ce=L&&!ye&&!Ge;Ce?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ue=Ce?Dt:m||ye?"none":Dt,Mt=Ce?D:ye?"none":m?st?"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":D;i&&!ye&&!Ce&&(Mt="none",Ue="none");let ut=Ce?Ne:m||ye?"0":Ne,wt=V(H?.border,Ue),xt=V(H?.shadow,Mt),qt=V(H?.borderRadius,ut),Vo=gs(),ft=Vo==="detached",ce=Vo==="welded";e.classList.toggle("persona-artifact-detached-split",ft),e.classList.toggle("persona-artifact-welded-split",ce);let At="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(o)&&Np(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",rt);let $e=ft||rt?"none":xt,et=ft?Dt:ce?"none":wt,Pt=ft?Ne:qt;rt&&(et="none",Pt="0");let Be=H?.borderRadius!=null&&H.borderRadius!=="",tt=rt&&!Be?"0":qt,ln=ie.scrollTop;e.style.cssText="",Me.style.cssText="",me.style.cssText="",ue.style.cssText="",ie.style.cssText="",j.style.cssText="",ke&&(ie.style.display="none");let zo=()=>{if(ln<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===ln)return;let tn=ie.scrollHeight-ie.clientHeight;tn<=0||(ie.scrollTop=Math.min(ln,tn))})};if(ye){Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Me.style.cssText=`
|
|
36
50
|
position: fixed !important;
|
|
37
51
|
inset: 0 !important;
|
|
38
52
|
width: 100% !important;
|
|
@@ -42,9 +56,9 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
42
56
|
padding: 0 !important;
|
|
43
57
|
display: flex !important;
|
|
44
58
|
flex-direction: column !important;
|
|
45
|
-
z-index: ${
|
|
59
|
+
z-index: ${jt} !important;
|
|
46
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
47
|
-
`,
|
|
61
|
+
`,me.style.cssText=`
|
|
48
62
|
position: relative !important;
|
|
49
63
|
display: flex !important;
|
|
50
64
|
flex-direction: column !important;
|
|
@@ -57,7 +71,7 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
57
71
|
padding: 0 !important;
|
|
58
72
|
box-shadow: none !important;
|
|
59
73
|
border-radius: 0 !important;
|
|
60
|
-
`,
|
|
74
|
+
`,ue.style.cssText=`
|
|
61
75
|
display: flex !important;
|
|
62
76
|
flex-direction: column !important;
|
|
63
77
|
flex: 1 1 0% !important;
|
|
@@ -68,20 +82,33 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
82
|
overflow: hidden !important;
|
|
69
83
|
border-radius: 0 !important;
|
|
70
84
|
border: none !important;
|
|
71
|
-
`,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0",F=!0,zo();return}let ks=o?.launcher?.width??o?.launcherWidth??pn;if(!m&&!i)v&&x?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=ks,me.style.maxWidth=ks);else if(i)if(on(o).reveal==="emerge"&&!L){let tn=on(o).width;me.style.width=tn,me.style.maxWidth=tn}else me.style.width="100%",me.style.maxWidth="100%";if(ms(),me.style.boxShadow=$e,me.style.borderRadius=tt,ft?me.style.border="none":ce&&(me.style.border=wt),ue.style.border=et,ue.style.borderRadius=Pt,ue.style.boxShadow=ft&&!rt?At:"",rt&&(ue.style.background="transparent",ie.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),ce){let Rt=o.features?.artifacts?.layout;ds=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||qt}else ds=null;if(i&&!ye&&!Ce&&!ft&&!ce&&H?.border===void 0&&(ue.style.border="none",on(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!ye&&ce&&H?.border===void 0&&(on(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),x&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",v&&(Me.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",ft||(me.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",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0"),v&&(Ce||ft||rt)&&!i&&(rt||(Me.style.padding="var(--persona-panel-inset)"),Me.style.background="var(--persona-panel-canvas-bg)"),Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!v&&!i&&(Ln[yt]??Ln["bottom-right"]).split(" ").forEach(tn=>Me.classList.add(tn)),m){let Rt=o.launcher?.sidebarWidth??"420px";L?Me.style.cssText=`
|
|
86
|
+
position: fixed !important;
|
|
87
|
+
top: var(--persona-panel-inset) !important;
|
|
88
|
+
bottom: var(--persona-panel-inset) !important;
|
|
89
|
+
width: ${Rt} !important;
|
|
90
|
+
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
91
|
+
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
92
|
+
margin: 0 !important;
|
|
93
|
+
padding: 0 !important;
|
|
94
|
+
display: flex !important;
|
|
95
|
+
flex-direction: column !important;
|
|
96
|
+
z-index: ${jt} !important;
|
|
97
|
+
${st?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
|
+
`:Me.style.cssText=`
|
|
99
|
+
position: fixed !important;
|
|
100
|
+
top: 0 !important;
|
|
101
|
+
bottom: 0 !important;
|
|
102
|
+
width: ${Rt} !important;
|
|
103
|
+
height: 100vh !important;
|
|
104
|
+
max-height: 100vh !important;
|
|
105
|
+
margin: 0 !important;
|
|
106
|
+
padding: 0 !important;
|
|
107
|
+
display: flex !important;
|
|
108
|
+
flex-direction: column !important;
|
|
109
|
+
z-index: ${jt} !important;
|
|
110
|
+
${st?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
+
`,me.style.cssText=`
|
|
85
112
|
position: relative !important;
|
|
86
113
|
display: flex !important;
|
|
87
114
|
flex-direction: column !important;
|
|
@@ -92,9 +119,10 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
92
119
|
min-height: 0 !important;
|
|
93
120
|
margin: 0 !important;
|
|
94
121
|
padding: 0 !important;
|
|
95
|
-
box-shadow: ${
|
|
96
|
-
border-radius: ${
|
|
97
|
-
|
|
122
|
+
box-shadow: ${$e} !important;
|
|
123
|
+
border-radius: ${tt} !important;
|
|
124
|
+
${ft?"border: none !important;":ce?`border: ${wt} !important;`:""}
|
|
125
|
+
`,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
|
|
98
126
|
display: flex !important;
|
|
99
127
|
flex-direction: column !important;
|
|
100
128
|
flex: 1 1 0% !important;
|
|
@@ -103,29 +131,32 @@ _Details: ${r.message}_`:o}var Ps=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
103
131
|
min-height: 0 !important;
|
|
104
132
|
max-height: 100% !important;
|
|
105
133
|
overflow: hidden !important;
|
|
106
|
-
border-radius: ${
|
|
107
|
-
border: ${
|
|
108
|
-
|
|
134
|
+
border-radius: ${Pt} !important;
|
|
135
|
+
border: ${et} !important;
|
|
136
|
+
${ft&&!rt?`box-shadow: ${At} !important;`:""}
|
|
137
|
+
${rt?"background: transparent !important;":""}
|
|
138
|
+
`,j.style.cssText=`
|
|
109
139
|
flex-shrink: 0 !important;
|
|
110
140
|
border-top: none !important;
|
|
111
141
|
padding: 8px 16px 12px 16px !important;
|
|
112
|
-
`}if(!b&&!l){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Bt=f?"":"padding-top: 1.25em !important;",$t=f?"":`z-index: ${(Ze=(ta=o.launcher)==null?void 0:ta.zIndex)!=null?Ze:Sr} !important;`;fe.style.cssText+=Dt+Bt+$t}Xe()};gn(),Bn(e,o),pl(e,o),ul(e,o);let it=[];it.push(()=>{document.removeEventListener("keydown",$o)}),it.push(()=>{po!==null&&clearTimeout(po)});let nr=null,ar=null;it.push(()=>{nr==null||nr(),nr=null,ar==null||ar(),ar=null}),Or&&it.push(()=>{Or==null||Or.disconnect(),Or=null}),it.push(()=>{eo==null||eo(),eo=null,va(),Nt&&(Nt.remove(),Nt=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ie&&it.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Ee==null||Ee.destroy(),Ee=null,j==null||j.destroy(),j=null,Te=null});let Lo=null,ns=()=>{Lo&&(Lo(),Lo=null),o.colorScheme==="auto"&&(Lo=qi(()=>{Bn(e,o)}))};ns(),it.push(()=>{Lo&&(Lo(),Lo=null)}),it.push(s);let Go=(bf=o.features)==null?void 0:bf.streamAnimation;if(Go!=null&&Go.type&&Go.type!=="none"){let l=ja(Go.type,Go.plugins);l&&(Ji(l,e),it.push(()=>ix(e)))}let jn=Ex(Vt),Po=null,q,wa=l=>{var b,P;if(!q)return;let f=l!=null?l:q.getMessages(),x=((P=(b=o.features)==null?void 0:b.suggestReplies)==null?void 0:P.enabled)!==!1?fi(f):null;x?jn.render(x,q,xe,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(B=>B.role==="user")?jn.render([],q,xe,f):jn.render(o.suggestionChips,q,xe,f,o.suggestionChipsConfig)},to=!1,Ro=Yh(),Ko=new Map,Io=new Map,fo=new Map,Ca=0,Xs=na()!==null,vr=$i(),Tr=0,mo=null,Er=!1,Gn=!1,go=0,wr=null,Wo=null,Sa=!1,Kn=!1,Aa=null,hn=!0,xn=!1,rt=null,L=4,$=24,z=80,K=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},De=(wf=(vf=o.voiceRecognition)==null?void 0:vf.autoResume)!=null?wf:!1,tt=l=>{i.emit("voice:state",{active:G.active,source:l,timestamp:Date.now()})},lt=()=>{y(l=>({...l,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},Sl=()=>{var b,P;if(((b=o.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Ip(p.voiceState),f=!!l.active,x=Number((P=l.timestamp)!=null?P:0);G.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-x<Q0&&setTimeout(()=>{var B,V;G.active||(G.manuallyDeactivated=!1,((V=(B=o.voiceRecognition)==null?void 0:B.provider)==null?void 0:V.type)==="runtype"?q.toggleVoice().then(()=>{G.active=q.isVoiceActive(),tt("restore"),q.isVoiceActive()&&ka()}):Ys("restore"))},1e3)},yn=()=>q?jx(q.getMessages()).filter(l=>!l.__skipPersist):[],kr=null,ur=(l,f)=>{typeof console!="undefined"&&console.error(l,f)},Xo=(l,f)=>{let x=()=>{try{let V=l();return!V||typeof V.then!="function"?null:Promise.resolve(V).catch(U=>{ur(f,U)})}catch(V){return ur(f,V),null}},b=kr,P=b?b.then(()=>{var V;return(V=x())!=null?V:void 0}):x();if(!P)return;let B=P.finally(()=>{kr===B&&(kr=null)});kr=B};function Ho(l){if(!(d!=null&&d.save))return;let x={messages:l?jx(l):q?yn():[],metadata:p,artifacts:_r.artifacts,selectedArtifactId:_r.selectedId};Xo(()=>d.save(x),"[AgentWidget] Failed to persist state:")}let sr=null,Lr=()=>fe.querySelector("#persona-scroll-container")||ve,gr=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null),Er=!1},Xp=()=>{mo!==null&&(cancelAnimationFrame(mo),mo=null),Gn=!1,gr()},Ry=()=>to&&Ml()&&(Ft()!=="anchor-top"||lo()),Al=()=>{let l=bt()||"Jump to latest",f=Ry();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),go>0?(Fr.textContent=String(go),Fr.style.display="",zt.setAttribute("aria-label",`${l} (${go} new)`)):(Fr.textContent="",Fr.style.display="none",zt.setAttribute("aria-label",f?`${l} (response streaming below)`:l))},Qp=()=>{go!==0&&(go=0,Al())},Ml=()=>er()?!vr.isFollowing():!Dn(ve,$),qr=()=>{if(!Qt()||te){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Ce&&Ce.appendChild(zt),Qr();let f=Oo(ve)>0&&Ml();f?Al():Qp(),zt.style.display=f?"":"none"},as=()=>{vr.pause()&&(Xp(),qr())},bn=()=>{vr.resume(),Qp(),qr()},vn=(l=!1)=>{er()&&vr.isFollowing()&&(!l&&!to||(mo!==null&&(cancelAnimationFrame(mo),mo=null),Gn=!0,mo=requestAnimationFrame(()=>{mo=null,Gn=!1,vr.isFollowing()&&Iy(Lr(),l?220:140)})))},Jp=(l,f,x,b=()=>!0)=>{let P=l.scrollTop,B=f(),V=B-P;if(gr(),Math.abs(V)<1){Er=!0,l.scrollTop=B,Tr=l.scrollTop,Er=!1;return}let U=performance.now();Er=!0;let _=re=>1-Math.pow(1-re,3),ne=re=>{if(!b()){gr();return}let J=f();J!==B&&(B=J,V=B-P);let be=re-U,Fe=Math.min(be/x,1),Ne=_(Fe),Ue=P+V*Ne;l.scrollTop=Ue,Tr=l.scrollTop,Fe<1?sr=requestAnimationFrame(ne):(l.scrollTop=B,Tr=l.scrollTop,sr=null,Er=!1)};sr=requestAnimationFrame(ne)},Iy=(l,f=500)=>{let x=Oo(l)-l.scrollTop;if(Math.abs(x)<1){Tr=l.scrollTop;return}if(Math.abs(x)>=z){gr(),Er=!0,l.scrollTop=Oo(l),Tr=l.scrollTop,Er=!1;return}Jp(l,()=>Oo(l),f,()=>vr.isFollowing())},Yp=()=>{let l=Lr();Er=!0,l.scrollTop=Oo(l),Tr=l.scrollTop,Er=!1,qr()},Zp=l=>{let f=0,x=l;for(;x&&x!==ve;)f+=x.offsetTop,x=x.offsetParent;return f},eu=()=>{var B;if(Uo()!=="last-user-turn")return!1;let l=(B=q==null?void 0:q.getMessages())!=null?B:[];if(l.length<2)return!1;let f=[...l].reverse().find(V=>V.role==="user");if(!f)return!1;let x=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ve.querySelector(`[data-message-id="${x}"]`);if(!b)return!1;let P=Math.min(Math.max(0,Zp(b)-So()),Oo(ve));return Er=!0,ve.scrollTop=P,Tr=ve.scrollTop,Er=!1,Ft()==="follow"&&!Dn(ve,$)&&vr.pause(),qr(),!0},tu=l=>{Wr.style.height=`${Math.max(0,Math.round(l))}px`,wr&&(wr.spacerHeight=Math.max(0,l))},ss=()=>{Wo!==null&&(cancelAnimationFrame(Wo),Wo=null),gr(),wr=null,Wr.style.height="0px"},Wy=l=>{Wo!==null&&cancelAnimationFrame(Wo),Wo=requestAnimationFrame(()=>{var _;Wo=null;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ve.querySelector(`[data-message-id="${f}"]`);if(!x)return;let b=Zp(x),P=(_=wr==null?void 0:wr.spacerHeight)!=null?_:0,B=ve.scrollHeight-P,{targetScrollTop:V,spacerHeight:U}=ox({anchorOffsetTop:b,topOffset:So(),viewportHeight:ve.clientHeight,contentHeight:B});wr={initialSpacerHeight:U,contentHeightAtAnchor:B,spacerHeight:U},tu(U),Jp(ve,()=>V,220)})},Hy=()=>{if(er()){if(!vr.isFollowing()||Dn(ve,1))return;vn(!to);return}if(wr&&wr.initialSpacerHeight>0){let l=ve.scrollHeight-wr.spacerHeight,f=nx({initialSpacerHeight:wr.initialSpacerHeight,contentHeightAtAnchor:wr.contentHeightAtAnchor,currentContentHeight:l});f!==wr.spacerHeight&&tu(f)}qr()},By=l=>{let f=Ft();f==="follow"?(bn(),vn(!0)):f==="anchor-top"&&(hn=!1,xn=!0,Wy(l))},Dy=()=>{if(Ft()==="anchor-top"){if(xn){hn=!1;return}hn=!0,ss(),bn(),vn(!0)}},Fy=l=>{let f=new Map;l.forEach(x=>{let b=K.get(x.id);f.set(x.id,{streaming:x.streaming,role:x.role}),!b&&x.role==="assistant"&&(i.emit("assistant:message",x),!Kn&&(Ft()!=="anchor-top"||lo())&&Ml()&&(go+=1,Al(),qr(),ln(go===1?"1 new message below.":`${go} new messages below.`))),x.role==="assistant"&&(b!=null&&b.streaming)&&x.streaming===!1&&i.emit("assistant:complete",x),x.variant==="approval"&&x.approval&&(b?x.approval.status!=="pending"&&i.emit("approval:resolved",{approval:x.approval,decision:x.approval.status}):i.emit("approval:requested",{approval:x.approval,message:x}))}),K.clear(),f.forEach((x,b)=>{K.set(b,x)})},Ny=(l,f,x)=>{var ot,We,Pe,$e,Xe,xt;let b=document.createElement("div"),B=(()=>{var Be;let F=n.find(Re=>Re.renderLoadingIndicator);if(F!=null&&F.renderLoadingIndicator)return F.renderLoadingIndicator;if((Be=o.loadingIndicator)!=null&&Be.render)return o.loadingIndicator.render})(),V=(F,Be)=>Be==null?!1:typeof Be=="string"?(F.textContent=Be,!0):(F.appendChild(Be),!0),U=new Set,_=new Set,ne=n.some(F=>F.renderAskUserQuestion),re=[],J=[],be=o.enableComponentStreaming!==!1,Fe=o.approval!==!1,Ne=[];if(f.forEach(F=>{var hr,Vr,Ge,Rt,zr,Qn,Jn,Yn,Zn,Pa,Ra,Xt,ea,Sn,An,Zo,ta;U.add(F.id);let Be=ne&&en(F),Re=Fe&&F.variant==="approval"&&!!F.approval,Je=!Be&&F.role==="assistant"&&!F.variant&&be&&js(F);if(!Re&&fo.has(F.id)){let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),fo.delete(F.id)}if(!Je&&Io.has(F.id)){let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Io.delete(F.id)}let Pt=en(F)?`:${(hr=F.agentMetadata)!=null&&hr.askUserQuestionAnswered?"a":"u"}:${(Vr=F.agentMetadata)!=null&&Vr.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",Oe=Jh(F,Ca)+Pt,Gt=Be||Re||Je?null:Zh(Ro,F.id,Oe);if(Gt){b.appendChild(Gt.cloneNode(!0)),en(F)&&((Ge=F.toolCall)!=null&&Ge.id)&&((Rt=F.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((zr=F.agentMetadata)!=null&&zr.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Na(F,o,je.composerOverlay));return}let wt=null,lr=n.find(Ze=>!!(F.variant==="reasoning"&&Ze.renderReasoning||F.variant==="tool"&&Ze.renderToolCall||!F.variant&&Ze.renderMessage)),Br=(Qn=o.layout)==null?void 0:Qn.messages;if(en(F)&&((Jn=F.agentMetadata)==null?void 0:Jn.askUserQuestionAnswered)===!0){Ko.delete(F.id);let Ze=l.querySelector(`#wrapper-${F.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Ss(F)&&((Zn=(Yn=o.features)==null?void 0:Yn.suggestReplies)==null?void 0:Zn.enabled)!==!1)return;if(en(F)&&((Ra=(Pa=o.features)==null?void 0:Pa.askUserQuestion)==null?void 0:Ra.enabled)!==!1){let Ze=n.find(Dt=>typeof Dt.renderAskUserQuestion=="function");if(Ze&&At.current){let Dt=Ko.get(F.id),Bt=Dt!==Oe,$t=null;if(Bt){let{payload:Ut,complete:xr}=tn(F),$r=F.id,Do=()=>{var fr;return(fr=At.current)==null?void 0:fr.getMessages().find(mr=>mr.id===$r)};$t=Ze.renderAskUserQuestion({message:F,payload:Ut,complete:xr,resolve:fr=>{var no;let mr=Do();mr&&((no=At.current)==null||no.resolveAskUserQuestion(mr,fr))},dismiss:()=>{var mr,no,Mn;let fr=Do();(mr=fr==null?void 0:fr.agentMetadata)!=null&&mr.awaitingLocalTool&&((no=At.current)==null||no.markAskUserQuestionResolved(fr),(Mn=At.current)==null||Mn.resolveAskUserQuestion(fr,"(dismissed)"))},config:o})}let _t=Dt!=null;if(Bt&&$t===null&&!_t){((Xt=F.agentMetadata)==null?void 0:Xt.awaitingLocalTool)===!0&&!((ea=F.agentMetadata)!=null&&ea.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Na(F,o,je.composerOverlay));return}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${F.id}`,ft.setAttribute("data-wrapper-id",F.id),ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),b.appendChild(ft),re.push({messageId:F.id,fingerprint:Oe,bubble:$t});return}else{((Sn=F.agentMetadata)==null?void 0:Sn.awaitingLocalTool)===!0&&!((An=F.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(_.add(F.toolCall.id),Na(F,o,je.composerOverlay));return}}else if(Re){let Ze=(Zo=n.find(_t=>typeof _t.renderApproval=="function"))!=null?Zo:a,Bt=fo.get(F.id)!==Oe,$t=null;if(Bt&&(Ze!=null&&Ze.renderApproval)){let _t=F.id,ft=(Ut,xr)=>{var Do,fr,mr;let $r=(Do=At.current)==null?void 0:Do.getMessages().find(no=>no.id===_t);$r!=null&&$r.approval&&($r.approval.toolType==="webmcp"?(fr=At.current)==null||fr.resolveWebMcpApproval($r.id,Ut):(mr=At.current)==null||mr.resolveApproval($r.approval,Ut,xr))};$t=Ze.renderApproval({message:F,defaultRenderer:()=>dl(F,o),config:o,approve:Ut=>ft("approved",Ut),deny:Ut=>ft("denied",Ut)})}if(Bt&&$t===null){let _t=l.querySelector(`#wrapper-${F.id}`);_t==null||_t.removeAttribute("data-preserve-runtime"),fo.delete(F.id),wt=dl(F,o)}else{let _t=document.createElement("div");_t.className="persona-flex",_t.id=`wrapper-${F.id}`,_t.setAttribute("data-wrapper-id",F.id),_t.setAttribute("data-approval-plugin-stub","true"),_t.setAttribute("data-preserve-runtime","true"),b.appendChild(_t),Ne.push({messageId:F.id,fingerprint:Oe,bubble:$t});return}}else if(lr)if(F.variant==="reasoning"&&F.reasoning&&lr.renderReasoning){if(!Le)return;wt=lr.renderReasoning({message:F,defaultRenderer:()=>Cp(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&lr.renderToolCall){if(!He)return;wt=lr.renderToolCall({message:F,defaultRenderer:()=>Ap(F,o),config:o})}else lr.renderMessage&&(wt=lr.renderMessage({message:F,defaultRenderer:()=>{let Ze=Xa(F,x,Br,o.messageActions,nt,{loadingIndicatorRenderer:B,widgetConfig:o});return F.role!=="user"&&Lp(Ze,F,o,q),Ze},config:o}));if(!wt&&Je){let Ze=hl(F);if(Ze){let Dt=Io.get(F.id),Bt=Dt!==Oe,$t=o.wrapComponentDirectiveInBubble!==!1,_t=null;if(Bt){let ft=gl(Ze,{config:o,message:F,transform:x});if(ft)if($t){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${F.id}`,Ut.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let xr=document.createElement("div");xr.className="persona-mb-3 persona-text-sm persona-leading-relaxed",xr.innerHTML=x({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),Ut.appendChild(xr)}Ut.appendChild(ft),_t=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${F.id}`,Ut.setAttribute("data-message-id",F.id),Ut.setAttribute("data-persona-component-directive","true"),F.content&&F.content.trim()){let xr=document.createElement("div");xr.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",xr.innerHTML=x({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),Ut.appendChild(xr)}Ut.appendChild(ft),_t=Ut}}if(_t||Dt!=null){let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${F.id}`,ft.setAttribute("data-wrapper-id",F.id),ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),$t||ft.classList.add("persona-w-full"),b.appendChild(ft),J.push({messageId:F.id,fingerprint:Oe,bubble:_t});return}}}if(!wt)if(F.variant==="reasoning"&&F.reasoning){if(!Le)return;wt=Cp(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!He)return;wt=Ap(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;wt=dl(F,o)}else{let Ze=(ta=o.layout)==null?void 0:ta.messages;Ze!=null&&Ze.renderUserMessage&&F.role==="user"?wt=Ze.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):Ze!=null&&Ze.renderAssistantMessage&&F.role==="assistant"?wt=Ze.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):wt=Xa(F,x,Ze,o.messageActions,nt,{loadingIndicatorRenderer:B,widgetConfig:o}),F.role!=="user"&&wt&&Lp(wt,F,o,q)}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${F.id}`,Ht.setAttribute("data-wrapper-id",F.id),F.role==="user"&&Ht.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Ht.classList.add("persona-w-full"),Ht.appendChild(wt),ex(Ro,F.id,Oe,Ht),b.appendChild(Ht)}),je.composerOverlay&&je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!_.has(Re)&&Ln(je.composerOverlay,Re)}),(We=(ot=o.features)==null?void 0:ot.toolCallDisplay)!=null&&We.grouped){let F=[],Be=[];f.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&He){Be.push(Re);return}Be.length>1&&F.push(Be),Be=[]}),Be.length>1&&F.push(Be),F.forEach((Re,Je)=>{var hr,Vr;let Pt=Re.map(Ge=>Array.from(b.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id=`wrapper-tool-group-${Je}-${Re[0].id}`,Oe.setAttribute("data-wrapper-id",`tool-group-${Je}-${Re[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let lr=`Called ${Re.length} tools`,Br=(Vr=(hr=o.toolCall)==null?void 0:hr.renderGroupedSummary)==null?void 0:Vr.call(hr,{messages:Re,toolCalls:Re.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:lr,config:o});V(wt,Br)||(wt.textContent=lr);let Ht=document.createElement("div");Ht.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(wt,Ht),Oe.appendChild(Gt),Pt[0].before(Oe),Pt.forEach((Ge,Rt)=>{let zr=document.createElement("div");zr.className="persona-tool-group-item persona-relative",zr.setAttribute("data-persona-tool-group-item","true"),Rt<Pt.length-1&&zr.setAttribute("data-persona-tool-group-connector","true"),zr.appendChild(Ge),Ht.appendChild(zr)})})}tx(Ro,U);let Ue=f.some(F=>F.role==="assistant"&&F.streaming),ze=f[f.length-1],ut=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(to&&f.some(F=>F.role==="user")&&!Ue&&!ut){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:ma},Be=n.find(Je=>Je.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(F)),Re===null&&((Pe=o.loadingIndicator)!=null&&Pe.render)&&(Re=o.loadingIndicator.render(F)),Re===null&&(Re=ma()),Re){let Je=document.createElement("div"),Pt=(($e=o.loadingIndicator)==null?void 0:$e.showBubble)!==!1;Je.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(Re);let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id="wrapper-typing-indicator",Oe.setAttribute("data-wrapper-id","typing-indicator"),Oe.appendChild(Je),b.appendChild(Oe)}}if(!to&&f.length>0){let F=f[f.length-1],Be={config:o,lastMessage:F,messageCount:f.length},Re=n.find(Pt=>Pt.renderIdleIndicator),Je=null;if(Re!=null&&Re.renderIdleIndicator&&(Je=Re.renderIdleIndicator(Be)),Je===null&&((Xe=o.loadingIndicator)!=null&&Xe.renderIdle)&&(Je=o.loadingIndicator.renderIdle(Be)),Je){let Pt=document.createElement("div"),Oe=((xt=o.loadingIndicator)==null?void 0:xt.showBubble)!==!1;Pt.className=Oe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Je);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Pt),b.appendChild(Gt)}}if(Vi(l,b),re.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of re){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),Ko.set(F,Be))}if(Ko.size>0)for(let F of Ko.keys())U.has(F)||Ko.delete(F);if(J.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of J){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),Io.set(F,Be))}if(Io.size>0)for(let F of Io.keys())U.has(F)||Io.delete(F);if(Ne.length>0)for(let{messageId:F,fingerprint:Be,bubble:Re}of Ne){let Je=l.querySelector(`#wrapper-${F}`);Je&&Re!==null&&(Je.replaceChildren(Re),Je.setAttribute("data-bubble-fp",Be),fo.set(F,Be))}if(fo.size>0)for(let F of fo.keys())U.has(F)||fo.delete(F)},is=(l,f,x)=>{Ny(l,f,x),fn()},ls=null,Oy=()=>{var x;if(ls)return;let l=b=>{let P=b.composedPath();P.includes(fe)||st&&P.includes(st)||Ot(!1,"user")};ls=l,((x=e.ownerDocument)!=null?x:document).addEventListener("pointerdown",l,!0)},ru=()=>{var f;if(!ls)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("pointerdown",ls,!0),ls=null};it.push(()=>ru());let ds=null,_y=()=>{var x;if(ds)return;let l=b=>{b.key==="Escape"&&(b.isComposing||Ot(!1,"user"))};ds=l,((x=e.ownerDocument)!=null?x:document).addEventListener("keydown",l,!0)},ou=()=>{var f;if(!ds)return;((f=e.ownerDocument)!=null?f:document).removeEventListener("keydown",ds,!0),ds=null};it.push(()=>ou());let cs=!1,nu=new Set,Uy=()=>{var f,x,b,P;let l=(b=(x=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:x.peek)==null?void 0:b.streamAnimation;return l||((P=o.features)==null?void 0:P.streamAnimation)},Ma=()=>{var ut,ot,We,Pe;if(!R())return;let l=je.peekBanner,f=je.peekTextNode;if(!l||!f)return;if(O){l.classList.remove("persona-pill-peek--visible");return}let x=(ut=q==null?void 0:q.getMessages())!=null?ut:[],b;for(let $e=x.length-1;$e>=0;$e--){let Xe=x[$e];if(Xe.role==="assistant"&&Xe.content){b=Xe;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let P=b.content,B=!!b.streaming,V=Uy(),U=Ki(V),_=U.type!=="none"?ja(U.type,V==null?void 0:V.plugins):null,ne=((ot=_==null?void 0:_.isAnimating)==null?void 0:ot.call(_,b))===!0,re=_!==null&&(B||ne);re&&_&&!nu.has(_.name)&&(Ji(_,e),nu.add(_.name));let J=re&&(_!=null&&_.containerClass)?_.containerClass:null,be=(We=f.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==J&&(f.classList.remove(be),delete f.dataset.personaPeekStreamClass),J&&be!==J&&(f.classList.add(J),f.dataset.personaPeekStreamClass=J),re?(f.style.setProperty("--persona-stream-step",`${U.speed}ms`),f.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Fe=re?Xi(P,U.buffer,_,b,B):P;if(re&&U.placeholder==="skeleton"&&B&&(!Fe||!Fe.trim())){let $e=document.createElement("div"),Xe=Ds();Xe.classList.add("persona-pill-peek__skeleton"),$e.appendChild(Xe),Vi(f,$e)}else{let $e=Math.max(0,Fe.length-100),Xe=Fe.length>100?Fe.slice(-100):Fe,xt=Fo(Xe);if(!re||!_){let F=Fe.length>100?`\u2026${Xe}`:Xe;f.textContent!==F&&(f.textContent=F)}else{let F=xt;(_.wrap==="char"||_.wrap==="word")&&(F=Bs(xt,_.wrap,`peek-${b.id}`,{skipTags:_.skipTags,startIndex:$e}));let Be=document.createElement("div");if(Be.innerHTML=F,_.useCaret&&Xe.length>0){let Re=Qi(),Je=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Je[Je.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(Re,Pt.nextSibling):Be.appendChild(Re)}Vi(f,Be),(Pe=_.onAfterRender)==null||Pe.call(_,{container:f,bubble:l,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let ze=to||cs;l.classList.toggle("persona-pill-peek--visible",ze)};if(R()){let l=je.peekBanner;if(l){let b=P=>{P.preventDefault(),P.stopPropagation(),Ot(!0,"user")};l.addEventListener("pointerdown",b),it.push(()=>{l.removeEventListener("pointerdown",b)})}let f=()=>{cs||(cs=!0,Ma())},x=()=>{cs&&(cs=!1,Ma())};X.addEventListener("pointerenter",f),X.addEventListener("pointerleave",x),it.push(()=>{X.removeEventListener("pointerenter",f),X.removeEventListener("pointerleave",x)}),st&&(st.addEventListener("pointerenter",f),st.addEventListener("pointerleave",x),it.push(()=>{st.removeEventListener("pointerenter",f),st.removeEventListener("pointerleave",x)}))}let qy=l=>{var be,Fe,Ne,Ue,ze,ut,ot,We;let f=(Fe=(be=o.launcher)==null?void 0:be.composerBar)!=null?Fe:{},x=(Ne=f.expandedSize)!=null?Ne:"anchored",b=(Ue=f.bottomOffset)!=null?Ue:"16px",P=f.collapsedMaxWidth,B=(ze=f.expandedMaxWidth)!=null?ze:"880px",V=(ut=f.expandedTopOffset)!=null?ut:"5vh",U=(ot=f.modalMaxWidth)!=null?ot:"880px",_=(We=f.modalMaxHeight)!=null?We:"min(90vh, 800px)",ne="calc(100vw - 32px)",re="var(--persona-pill-area-height, 80px)",J=fe.style;if(J.left="",J.right="",J.top="",J.bottom="",J.transform="",J.width="",J.maxWidth="",J.height="",J.maxHeight="",st){let Pe=st.style;Pe.bottom=b,Pe.width=P!=null?P:""}if(l&&x!=="fullscreen"){if(x==="modal"){J.top="50%",J.left="50%",J.transform="translate(-50%, -50%)",J.bottom="auto",J.right="auto",J.width=U,J.maxWidth=ne,J.maxHeight=_,J.height=_;return}J.left="50%",J.transform="translateX(-50%)",J.bottom=`calc(${b} + ${re})`,J.top=V,J.width=B,J.maxWidth=ne}},ps=()=>{var _,ne,re,J,be,Fe,Ne,Ue;if(!D())return;if(R()){let ut=(re=((ne=(_=o.launcher)==null?void 0:_.composerBar)!=null?ne:{}).expandedSize)!=null?re:"anchored",ot=O?"expanded":"collapsed";fe.dataset.state=ot,fe.dataset.expandedSize=ut,st&&(st.dataset.state=ot,st.dataset.expandedSize=ut),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qy(O),Ce.style.display=O?"flex":"none",gn(),O?(Oy(),_y()):(ru(),ou()),Ma();return}let l=or(o),f=(J=e.ownerDocument.defaultView)!=null?J:window,x=(Fe=(be=o.launcher)==null?void 0:be.mobileBreakpoint)!=null?Fe:640,b=(Ue=(Ne=o.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ue:!0,P=f.innerWidth<=x,B=b&&P&&k,V=Kr(o).reveal;O?(fe.style.removeProperty("display"),fe.style.display=l?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":ir&&(ir.style.display="none")):(l?l&&(V==="overlay"||V==="push")&&!B?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=l?"none":"":ir&&(ir.style.display=l?"none":""))},Ot=(l,f="user")=>{var B,V;if(!D()||O===l)return;let x=O;O=l,ps();let b=(()=>{var Ne,Ue,ze,ut,ot,We,Pe,$e,Xe,xt;let U=(Ue=(Ne=o.launcher)==null?void 0:Ne.sidebarMode)!=null?Ue:!1,_=(ze=e.ownerDocument.defaultView)!=null?ze:window,ne=(ot=(ut=o.launcher)==null?void 0:ut.mobileFullscreen)!=null?ot:!0,re=(Pe=(We=o.launcher)==null?void 0:We.mobileBreakpoint)!=null?Pe:640,J=_.innerWidth<=re,be=or(o)&&ne&&J,Fe=R()&&((xt=(Xe=($e=o.launcher)==null?void 0:$e.composerBar)==null?void 0:Xe.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return U||ne&&J&&k||be||Fe})();if(O&&b){if(!nr){let U=e.getRootNode(),_=U instanceof ShadowRoot?U.host:e.closest(".persona-host");_&&(nr=pp(_,(V=(B=o.launcher)==null?void 0:B.zIndex)!=null?V:Sr))}ar||(ar=up(e.ownerDocument))}else O||(nr==null||nr(),nr=null,ar==null||ar(),ar=null);O&&(us(),eu()||(Ft()==="follow"?vn(!0):Yp()));let P={open:O,source:f,timestamp:Date.now()};O&&!x?i.emit("widget:opened",P):!O&&x&&i.emit("widget:closed",P),i.emit("widget:state",{open:O,launcherEnabled:k,voiceActive:G.active,streaming:q.isStreaming()})},Tl=l=>{pe(l?"stop":"send"),N&&(N.disabled=l),jn.buttons.forEach(f=>{f.disabled=l}),Ie.dataset.personaComposerStreaming=l?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},El=()=>{G.active||xe&&xe.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>El(),200)});let au=()=>{var x,b,P,B,V,U,_,ne,re,J,be;wo.textContent=(b=(x=o.copy)==null?void 0:x.welcomeTitle)!=null?b:"Hello \u{1F44B}",Co.textContent=(B=(P=o.copy)==null?void 0:P.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",xe.placeholder=(U=(V=o.copy)==null?void 0:V.inputPlaceholder)!=null?U:"How can I help...";let l=ve.querySelector("[data-persona-intro-card]");if(l){let Fe=((_=o.copy)==null?void 0:_.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((re=(ne=o.sendButton)==null?void 0:ne.useIcon)!=null&&re)&&!(q!=null&&q.isStreaming())&&(de.textContent=(be=(J=o.copy)==null?void 0:J.sendButtonLabel)!=null?be:"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{y(f=>({...f,sessionId:l}))}});let Xn=null,Vy=()=>{Xn==null&&(Xn=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Xn),Xn=null;return}let f=Date.now();l.forEach(x=>{let b=Number(x.getAttribute("data-tool-elapsed"));b&&(x.textContent=gi(f-b))})},100))},kl=(l,f)=>{if(Object.is(l,f))return!0;if(l===null||f===null||typeof l!="object"||typeof f!="object")return!1;if(Array.isArray(l)||Array.isArray(f))return!Array.isArray(l)||!Array.isArray(f)||l.length!==f.length?!1:l.every((V,U)=>kl(V,f[U]));let x=l,b=f,P=Object.keys(x),B=Object.keys(b);return P.length===B.length&&P.every(V=>Object.prototype.hasOwnProperty.call(b,V)&&kl(x[V],b[V]))},su=l=>{let{content:f,rawContent:x,llmContent:b,...P}=l;return P},Ll=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!js(l),zy=(l,f,x)=>{if(l.length!==f.length)return!1;let b=l[x.index],P=f[x.index];return!b||!P||b.id!==x.id||P.id!==x.id?!1:(!Object.is(b.content,P.content)||!Object.is(b.rawContent,P.rawContent)||!Object.is(b.llmContent,P.llmContent))&&Ll(b)&&Ll(P)&&kl(su(b),su(P))},iu=null,Ta=null,Qo=null,Jo=null,Qs=l=>{var P,B;iu=l;let f,x;Ta=null;for(let V=l.length-1;V>=0;V-=1){let U=l[V];if(!f&&U.role==="user"&&(f=U),!x&&U.role==="assistant"&&(x=U),!Ta&&Ll(U)&&(Ta={index:V,id:U.id}),f&&x&&Ta)break}is(Ye,l,Z),Vy(),wa(l),vn(!to),Fy(l),l.length===0&&(ss(),hn=!0,xn=!1),!Sa||Kn?(Sa=!0,Aa=(P=f==null?void 0:f.id)!=null?P:null,rt=(B=x==null?void 0:x.id)!=null?B:null):f&&f.id!==Aa?(Aa=f.id,By(f.id)):x&&x.id!==rt&&Dy(),x&&(rt=x.id);let b=G.lastUserMessageId;f&&f.id!==b&&(G.lastUserMessageId=f.id,i.emit("user:message",f)),G.lastUserMessageWasVoice=!!(f!=null&&f.viaVoice),Ho(l),Ma()},Pl=()=>{Jo!==null&&(cancelAnimationFrame(Jo),Jo=null);let l=Qo;Qo=null,l&&Qs(l)},lu=()=>{Jo!==null&&cancelAnimationFrame(Jo),Jo=null,Qo=null},$y=l=>{let f=Qo!=null?Qo:iu;if(to&&f&&Ta&&zy(f,l,Ta)){Qo=l,Jo===null&&(Jo=requestAnimationFrame(()=>{Jo=null;let x=Qo;Qo=null,x&&Qs(x)}));return}if(l.length===0){lu(),Qs(l);return}Pl(),Qs(l)};q=new qa(o,{onMessagesChanged(l){$y(l)},onStatusChanged(l){var b;let f=(b=o.statusIndicator)!=null?b:{};jt(br,(P=>{var B,V,U,_,ne,re;return P==="idle"?(B=f.idleText)!=null?B:rr.idle:P==="connecting"?(V=f.connectingText)!=null?V:rr.connecting:P==="connected"?(U=f.connectedText)!=null?U:rr.connected:P==="error"?(_=f.errorText)!=null?_:rr.error:P==="paused"?(ne=f.pausedText)!=null?ne:rr.paused:P==="resuming"?(re=f.resumingText)!=null?re:rr.resuming:rr[P]})(l),f,l)},onStreamingChanged(l){l||((q==null?void 0:q.getMessages().length)===0?lu():Pl()),to=l,Tl(l),q&&is(Ye,q.getMessages(),Z),l||vn(!0),qr(),ln(l?"Responding\u2026":"Response complete."),Ma()},onVoiceStatusChanged(l){var f,x;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((x=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:x.type)==="runtype")switch(l){case"listening":Yo(),ka();break;case"processing":Yo(),Qy();break;case"speaking":Yo(),Jy();break;default:l==="idle"&&q.isBargeInActive()?(Yo(),ka(),N==null||N.setAttribute("aria-label","End voice session")):(G.active=!1,Yo(),tt("system"),lt());break}},onArtifactsState(l){_r=l,ko(),Ho()},onReconnect(l){var b;let{executionId:f,lastEventId:x}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:f,after:x}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:f,after:x,attempt:(b=l.attempt)!=null?b:1}):i.emit("stream:resumed",{executionId:f,after:x})}}),At.current=q,it.push(()=>q.cancel());let Rl=null;if(q.onReadAloudChange((l,f)=>{var P;pn=l,un=f,fn();let x=l!=null?l:Rl;l&&(Rl=l);let b=x&&(P=q.getMessages().find(B=>B.id===x))!=null?P:null;i.emit("message:read-aloud",{messageId:x,message:b,state:f,timestamp:Date.now()}),f==="idle"&&(Rl=null)}),Sa=!0,((Sf=(Cf=o.voiceRecognition)==null?void 0:Cf.provider)==null?void 0:Sf.type)==="runtype")try{q.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&q.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(j||o.onSSEEvent)&&q.setSSEEventCallback((l,f)=>{var x;(x=o.onSSEEvent)==null||x.call(o,l,f),ee==null||ee.processEvent(l,f),j==null||j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})});let du=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};m?m.then(l=>{var f,x,b;if(l){if(l.metadata&&(p=Ip(l.metadata),A.syncFromMetadata()),(f=l.messages)!=null&&f.length){Kn=!0;try{q.hydrateMessages(l.messages)}finally{Kn=!1}}(x=l.artifacts)!=null&&x.length&&q.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>du()):du();let cu=()=>{var f,x,b;!R()||O||!((b=(x=(f=o.launcher)==null?void 0:f.composerBar)==null?void 0:x.expandOnSubmit)==null||b)||Ot(!0,"auto")},pu=l=>{var P;if(l.preventDefault(),q.isStreaming()){q.cancel(),ee==null||ee.reset(),Ee==null||Ee.update();return}let f=xe.value.trim(),x=(P=St==null?void 0:St.hasAttachments())!=null?P:!1;if(!f&&!x)return;cu();let b;x&&(b=[],b.push(...St.getContentParts()),f&&b.push(Es(f))),xe.value="",xe.style.height="auto",Js(),q.sendMessage(f,{contentParts:b}),x&&St.clearAttachments()},jy=()=>{var l;return((l=o.features)==null?void 0:l.composerHistory)!==!1},Il={...zi},Wl=!1,Js=()=>{Il={...zi}},Gy=()=>q.getMessages().filter(l=>l.role==="user").map(l=>{var f;return(f=l.content)!=null?f:""}).filter(l=>l.length>0),Ky=l=>{if(!xe)return;Wl=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),Wl=!1;let f=xe.value.length;xe.setSelectionRange(f,f)},uu=()=>{Wl||Js()},fu=l=>{if(xe){if(jy()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=xe.selectionStart===0&&xe.selectionEnd===0,x=Qh({direction:l.key==="ArrowUp"?"up":"down",history:Gy(),currentValue:xe.value,atStart:f,state:Il});if(Il=x.state,x.handled){l.preventDefault(),x.value!==void 0&&Ky(x.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(q.isStreaming()){l.preventDefault();return}Js(),l.preventDefault(),de.click()}}},mu=l=>{l.key!=="Escape"||l.isComposing||q.isStreaming()&&l.composedPath().includes(Ce)&&(q.cancel(),ee==null||ee.reset(),Ee==null||Ee.update(),Js(),l.preventDefault(),l.stopImmediatePropagation())},gu=async l=>{var x;if(((x=o.attachments)==null?void 0:x.enabled)!==!0||!St)return;let f=Y0(l.clipboardData);f.length!==0&&(l.preventDefault(),await St.handleFiles(f))},ro=null,Bo=!1,Ea=null,pt=null,hu=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ys=(l="user")=>{var B,V,U,_,ne,re,J;if(Bo||q.isStreaming())return;let f=hu();if(!f)return;ro=new f;let b=(V=((B=o.voiceRecognition)!=null?B:{}).pauseDuration)!=null?V:2e3;ro.continuous=!0,ro.interimResults=!0,ro.lang="en-US";let P=xe.value;ro.onresult=be=>{let Fe="",Ne="";for(let ze=0;ze<be.results.length;ze++){let ut=be.results[ze],ot=ut[0].transcript;ut.isFinal?Fe+=ot+" ":Ne=ot}let Ue=P+Fe+Ne;xe.value=Ue,Ea&&clearTimeout(Ea),(Fe||Ne)&&(Ea=window.setTimeout(()=>{let ze=xe.value.trim();ze&&ro&&Bo&&(wn(),xe.value="",xe.style.height="auto",q.sendMessage(ze,{viaVoice:!0}))},b))},ro.onerror=be=>{be.error!=="no-speech"&&wn()},ro.onend=()=>{if(Bo){let be=xe.value.trim();be&&be!==P.trim()&&(xe.value="",xe.style.height="auto",q.sendMessage(be,{viaVoice:!0})),wn()}};try{if(ro.start(),Bo=!0,G.active=!0,l!=="system"&&(G.manuallyDeactivated=!1),tt(l),lt(),N){let be=(U=o.voiceRecognition)!=null?U:{};pt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(_=be.iconName)!=null?_:"mic",iconSize:parseFloat((J=(re=be.iconSize)!=null?re:(ne=o.sendButton)==null?void 0:ne.size)!=null?J:"40")||24};let Fe=be.recordingBackgroundColor,Ne=be.recordingIconColor,Ue=be.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let ze=N.querySelector("svg");ze&&ze.setAttribute("stroke",Ne)}Ue&&(N.style.borderColor=Ue),N.setAttribute("aria-label","Stop voice recognition")}}catch{wn("system")}},wn=(l="user")=>{if(Bo){if(Bo=!1,Ea&&(clearTimeout(Ea),Ea=null),ro){try{ro.stop()}catch{}ro=null}if(G.active=!1,tt(l),lt(),N){if(N.classList.remove("persona-voice-recording"),pt){N.style.backgroundColor=pt.backgroundColor,N.style.color=pt.color,N.style.borderColor=pt.borderColor;let f=N.querySelector("svg");f&&f.setAttribute("stroke",pt.color||"currentColor"),pt=null}N.setAttribute("aria-label","Start voice recognition")}}},Xy=(l,f)=>{var ot,We,Pe,$e,Xe,xt,F,Be,Re;let x=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ot=l==null?void 0:l.provider)==null?void 0:ot.type)==="runtype",P=((We=l==null?void 0:l.provider)==null?void 0:We.type)==="custom";if(!(x||b||P))return null;let V=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",U.setAttribute("aria-label","Start voice recognition");let _=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",ne=($e=f==null?void 0:f.size)!=null?$e:"40px",re=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ne,J=parseFloat(re)||24,be=(xt=l==null?void 0:l.backgroundColor)!=null?xt:f==null?void 0:f.backgroundColor,Fe=(F=l==null?void 0:l.iconColor)!=null?F:f==null?void 0:f.textColor;U.style.width=re,U.style.height=re,U.style.minWidth=re,U.style.minHeight=re,U.style.fontSize="18px",U.style.lineHeight="1",Fe?U.style.color=Fe:U.style.color="var(--persona-text, #111827)";let Ue=he(_,J,Fe||"currentColor",1.5);Ue?U.appendChild(Ue):U.textContent="\u{1F3A4}",be?U.style.backgroundColor=be:U.style.backgroundColor="",l!=null&&l.borderWidth&&(U.style.borderWidth=l.borderWidth,U.style.borderStyle="solid"),l!=null&&l.borderColor&&(U.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(U.style.paddingLeft=l.paddingX,U.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(U.style.paddingTop=l.paddingY,U.style.paddingBottom=l.paddingY),V.appendChild(U);let ze=(Be=l==null?void 0:l.tooltipText)!=null?Be:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&ze){let Je=v("div","persona-send-button-tooltip");Je.textContent=ze,V.appendChild(Je)}return{micButton:U,micButtonWrapper:V}},Hl=()=>{var f,x,b,P,B;if(!N||pt)return;let l=(f=o.voiceRecognition)!=null?f:{};pt={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(x=l.iconName)!=null?x:"mic",iconSize:parseFloat((B=(P=l.iconSize)!=null?P:(b=o.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Bl=(l,f)=>{var B,V,U,_,ne;if(!N)return;let x=N.querySelector("svg");x&&x.remove();let b=(ne=pt==null?void 0:pt.iconSize)!=null?ne:parseFloat((_=(U=(B=o.voiceRecognition)==null?void 0:B.iconSize)!=null?U:(V=o.sendButton)==null?void 0:V.size)!=null?_:"40")||24,P=he(l,b,f,1.5);P&&N.appendChild(P)},Zs=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ka=()=>{var P;if(!N)return;Hl();let l=(P=o.voiceRecognition)!=null?P:{},f=l.recordingBackgroundColor,x=l.recordingIconColor,b=l.recordingBorderColor;if(Zs(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=f!=null?f:"var(--persona-voice-recording-bg, #ef4444)",N.style.color=x!=null?x:"var(--persona-voice-recording-indicator, #ffffff)",x){let B=N.querySelector("svg");B&&B.setAttribute("stroke",x)}b&&(N.style.borderColor=b),N.setAttribute("aria-label","Stop voice recognition")},Qy=()=>{var U,_,ne,re,J,be,Fe,Ne;if(!N)return;Hl();let l=(U=o.voiceRecognition)!=null?U:{},f=q.getVoiceInterruptionMode(),x=(_=l.processingIconName)!=null?_:"loader",b=(re=(ne=l.processingIconColor)!=null?ne:pt==null?void 0:pt.color)!=null?re:"",P=(be=(J=l.processingBackgroundColor)!=null?J:pt==null?void 0:pt.backgroundColor)!=null?be:"",B=(Ne=(Fe=l.processingBorderColor)!=null?Fe:pt==null?void 0:pt.borderColor)!=null?Ne:"";Zs(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=P,N.style.borderColor=B;let V=b||"currentColor";N.style.color=V,Bl(x,V),N.setAttribute("aria-label","Processing voice input"),f==="none"&&(N.style.cursor="default")},Jy=()=>{var ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,We,Pe;if(!N)return;Hl();let l=(ne=o.voiceRecognition)!=null?ne:{},f=q.getVoiceInterruptionMode(),x=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=(re=l.speakingIconName)!=null?re:x,P=(Ne=l.speakingIconColor)!=null?Ne:f==="barge-in"?(be=(J=l.recordingIconColor)!=null?J:pt==null?void 0:pt.color)!=null?be:"":(Fe=pt==null?void 0:pt.color)!=null?Fe:"",B=(ut=l.speakingBackgroundColor)!=null?ut:f==="barge-in"?(Ue=l.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=pt==null?void 0:pt.backgroundColor)!=null?ze:"",V=(Pe=l.speakingBorderColor)!=null?Pe:f==="barge-in"?(ot=l.recordingBorderColor)!=null?ot:"":(We=pt==null?void 0:pt.borderColor)!=null?We:"";Zs(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=B,N.style.borderColor=V;let U=P||"currentColor";N.style.color=U,Bl(b,U);let _=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",_),f==="none"&&(N.style.cursor="default"),f==="barge-in"&&N.classList.add("persona-voice-recording")},Yo=()=>{var l,f,x;N&&(Zs(),pt&&(N.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",N.style.color=(f=pt.color)!=null?f:"",N.style.borderColor=(x=pt.borderColor)!=null?x:"",Bl(pt.iconName,pt.color||"currentColor"),pt=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},ei=()=>{var l,f;if(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"){let x=q.getVoiceStatus(),b=q.getVoiceInterruptionMode();if(b==="none"&&(x==="processing"||x==="speaking"))return;if(b==="cancel"&&(x==="processing"||x==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,lt(),tt("user"),Yo()});return}q.toggleVoice().then(()=>{G.active=q.isVoiceActive(),G.manuallyDeactivated=!q.isVoiceActive(),lt(),tt("user"),q.isVoiceActive()?ka():Yo()});return}if(Bo){let x=xe.value.trim();G.manuallyDeactivated=!0,lt(),wn("user"),x&&(xe.value="",xe.style.height="auto",q.sendMessage(x))}else G.manuallyDeactivated=!1,lt(),Ys("user")};Mo=ei,N&&(N.addEventListener("click",ei),it.push(()=>{var l,f;((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Yo()):wn("system"),N&&N.removeEventListener("click",ei)}));let Yy=i.on("assistant:complete",()=>{De&&(G.active||G.manuallyDeactivated||De==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var l,f;!G.active&&!G.manuallyDeactivated&&(((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?q.toggleVoice().then(()=>{G.active=q.isVoiceActive(),tt("auto"),q.isVoiceActive()&&ka()}):Ys("auto"))},600))});it.push(Yy);let Zy=i.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});it.push(Zy);let xu=()=>{Ot(!O,"user")},Yt=null,ir=null;if(k&&!R()){let{instance:l,element:f}=xp({config:o,plugins:n,onToggle:xu});Yt=l,l||(ir=f)}Yt?e.appendChild(Yt.element):ir&&e.appendChild(ir),ps(),wa(),au(),Tl(q.isStreaming()),eu()||(Ft()==="follow"?vn(!0):Yp()),Sl(),C&&(!k||R()?setTimeout(()=>El(),0):O&&setTimeout(()=>El(),200));let us=()=>{var _,ne,re,J,be,Fe,Ne,Ue,ze,ut,ot,We,Pe,$e,Xe,xt,F,Be,Re,Je,Pt,Oe;if(R()){Qr(),ps();return}let l=or(o),f=(ne=(_=o.launcher)==null?void 0:_.sidebarMode)!=null?ne:!1,x=l||f||((J=(re=o.launcher)==null?void 0:re.fullHeight)!=null?J:!1),b=(be=e.ownerDocument.defaultView)!=null?be:window,P=(Ne=(Fe=o.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ne:!0,B=(ze=(Ue=o.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,V=b.innerWidth<=B,U=P&&V&&k;try{if(U){gn(),Bn(e,o);return}if(I&&(I=!1,gn(),Bn(e,o)),!k&&!l){X.style.height="",X.style.width="";return}if(!f&&!l){let Gt=(ot=(ut=o==null?void 0:o.launcher)==null?void 0:ut.width)!=null?ot:o==null?void 0:o.launcherWidth,wt=Gt!=null?Gt:Gr;X.style.width=wt,X.style.maxWidth=wt}if($n(),!x){let Gt=b.innerHeight,wt=64,lr=(Pe=(We=o.launcher)==null?void 0:We.heightOffset)!=null?Pe:0,Br=Math.max(200,Gt-wt),Ht=Math.min(640,Br),hr=Math.max(200,Ht-lr);X.style.height=`${hr}px`}}finally{if(Qr(),ps(),O&&k){let wt=(($e=e.ownerDocument.defaultView)!=null?$e:window).innerWidth<=((xt=(Xe=o.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?xt:640),lr=(Be=(F=o.launcher)==null?void 0:F.sidebarMode)!=null?Be:!1,Br=(Je=(Re=o.launcher)==null?void 0:Re.mobileFullscreen)!=null?Je:!0,Ht=or(o)&&Br&&wt,hr=lr||Br&&wt&&k||Ht;if(hr&&!ar){let Vr=e.getRootNode(),Ge=Vr instanceof ShadowRoot?Vr.host:e.closest(".persona-host");Ge&&!nr&&(nr=pp(Ge,(Oe=(Pt=o.launcher)==null?void 0:Pt.zIndex)!=null?Oe:Sr)),ar=up(e.ownerDocument)}else hr||(nr==null||nr(),nr=null,ar==null||ar(),ar=null)}}};us();let yu=(Af=e.ownerDocument.defaultView)!=null?Af:window;if(yu.addEventListener("resize",us),it.push(()=>yu.removeEventListener("resize",us)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Qr()});l.observe(Ie),it.push(()=>l.disconnect())}Tr=ve.scrollTop;let bu=Oo(ve),eb=()=>{let l=ve.getRootNode(),f=typeof l.getSelection=="function"?l.getSelection():null;return f!=null?f:ve.ownerDocument.getSelection()},Dl=()=>rx(eb(),ve),vu=()=>{let l=ve.scrollTop,f=Oo(ve),x=f<bu;if(bu=f,!er()){Tr=l,qr();return}let{action:b,nextLastScrollTop:P}=ji({following:vr.isFollowing(),currentScrollTop:l,lastScrollTop:Tr,nearBottom:Dn(ve,$),userScrollThreshold:L,isAutoScrolling:Er||Gn||x,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Tr=P,b==="resume"){Dl()||bn();return}b==="pause"&&as()};if(ve.addEventListener("scroll",vu,{passive:!0}),it.push(()=>ve.removeEventListener("scroll",vu)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Hy()});l.observe(Ye),l.observe(ve),it.push(()=>l.disconnect())}let wu=()=>{er()&&vr.isFollowing()&&Dl()&&as()},Cu=ve.ownerDocument;Cu.addEventListener("selectionchange",wu),it.push(()=>{Cu.removeEventListener("selectionchange",wu)});let tb=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Su=l=>{io()&&er()&&vr.isFollowing()&&tb.has(l.key)&&as()},Au=l=>{if(!io()||!er()||!vr.isFollowing())return;let f=l.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&as()};ve.addEventListener("keydown",Su),ve.addEventListener("focusin",Au),it.push(()=>{ve.removeEventListener("keydown",Su),ve.removeEventListener("focusin",Au)});let Mu=l=>{if(!er())return;let f=Gi({following:vr.isFollowing(),deltaY:l.deltaY,nearBottom:Dn(ve,$),resumeWhenNearBottom:!0});f==="pause"?as():f==="resume"&&!Dl()&&bn()};ve.addEventListener("wheel",Mu,{passive:!0}),it.push(()=>ve.removeEventListener("wheel",Mu)),zt.addEventListener("click",()=>{ss(),ve.scrollTop=ve.scrollHeight,Tr=ve.scrollTop,bn(),vn(!0),qr()}),it.push(()=>zt.remove()),it.push(()=>{Xp(),ss()});let Tu=()=>{Ve&&(Po&&(Ve.removeEventListener("click",Po),Po=null),D()?(Ve.style.display="",Po=()=>{Ot(!1,"user")},Ve.addEventListener("click",Po)):Ve.style.display="none")};Tu(),(()=>{let{clearChatButton:l}=je;l&&l.addEventListener("click",()=>{q.clearMessages(),Ro.clear(),bn(),Ln(je.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(x){console.error("[AgentWidget] Failed to clear default localStorage:",x)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(x){console.error("[AgentWidget] Failed to clear custom localStorage:",x)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d!=null&&d.clear&&Xo(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},A.syncFromMetadata(),j==null||j.clear(),ee==null||ee.reset(),Ee==null||Ee.update()})})(),Ct&&Ct.addEventListener("submit",pu),xe==null||xe.addEventListener("keydown",fu),xe==null||xe.addEventListener("input",uu),xe==null||xe.addEventListener("paste",gu);let Eu=(Mf=e.ownerDocument)!=null?Mf:document;Eu.addEventListener("keydown",mu,!0);let ku="persona-attachment-drop-active",fs=0,Fl=()=>{fs=0,Ce.classList.remove(ku)},La=()=>{var l;return((l=o.attachments)==null?void 0:l.enabled)===!0&&St!==null},Lu=l=>{!bl(l.dataTransfer)||!La()||(fs++,fs===1&&Ce.classList.add(ku))},Pu=l=>{!bl(l.dataTransfer)||!La()||(fs--,fs<=0&&Fl())},Ru=l=>{!bl(l.dataTransfer)||!La()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Iu=l=>{var x;if(!bl(l.dataTransfer)||!La())return;l.preventDefault(),l.stopPropagation(),Fl();let f=Array.from((x=l.dataTransfer.files)!=null?x:[]);f.length!==0&&St.handleFiles(f)},Cn=!0;Ce.addEventListener("dragenter",Lu,Cn),Ce.addEventListener("dragleave",Pu,Cn),e.addEventListener("dragover",Ru,Cn),e.addEventListener("drop",Iu,Cn);let ti=e.ownerDocument,Wu=l=>{La()&&l.preventDefault()},Hu=l=>{La()&&l.preventDefault()};ti.addEventListener("dragover",Wu),ti.addEventListener("drop",Hu),it.push(()=>{Ct&&Ct.removeEventListener("submit",pu),xe==null||xe.removeEventListener("keydown",fu),xe==null||xe.removeEventListener("input",uu),xe==null||xe.removeEventListener("paste",gu),Eu.removeEventListener("keydown",mu,!0)}),it.push(()=>{Ce.removeEventListener("dragenter",Lu,Cn),Ce.removeEventListener("dragleave",Pu,Cn),e.removeEventListener("dragover",Ru,Cn),e.removeEventListener("drop",Iu,Cn),ti.removeEventListener("dragover",Wu),ti.removeEventListener("drop",Hu),Fl()}),it.push(()=>{q.cancel()}),Yt?it.push(()=>{Yt==null||Yt.destroy()}):ir&&it.push(()=>{ir==null||ir.remove()});let tr={update(l){var $r,Do,fr,mr,no,Mn,If,Wf,Hf,Bf,Df,Ff,Nf,Of,_f,Uf,qf,Vf,zf,$f,jf,Gf,Kf,Xf,Qf,Jf,Yf,Zf,em,tm,rm,om,nm,am,sm,im,lm,dm,cm,pm,um,fm,mm,gm,hm,xm,ym,bm,vm,wm,Cm,Sm,Am,Mm,Tm,Em,km,Lm,Pm,Rm,Im,Wm,Hm,Bm,Dm,Fm,Nm,Om,_m,Um,qm,Vm,zm,$m,jm,Gm,Km,Xm,Qm,Jm,Ym,Zm,eg,tg,rg,og,ng,ag,sg,ig,lg,dg,cg,pg,ug,fg,mg,gg,hg,xg,yg,bg,vg,wg,Cg,Sg,Ag,Mg,Tg,Eg,kg,Lg,Pg,Rg,Ig,Wg,Hg,Bg,Dg,Fg,Ng;let f=o.toolCall,x=o.messageActions,b=($r=o.layout)==null?void 0:$r.messages,P=o.colorScheme,B=o.loadingIndicator,V=o.iterationDisplay,U=(Do=o.features)==null?void 0:Do.showReasoning,_=(fr=o.features)==null?void 0:fr.showToolCalls,ne=(mr=o.features)==null?void 0:mr.toolCallDisplay,re=(no=o.features)==null?void 0:no.reasoningDisplay,J=(If=(Mn=o.features)==null?void 0:Mn.streamAnimation)==null?void 0:If.type;o={...o,...l},gn(),Bn(e,o),pl(e,o),ul(e,o),ko(),o.colorScheme!==P&&ns();let be=Vs.getForInstance(o.plugins);n.length=0,n.push(...be),k=(Hf=(Wf=o.launcher)==null?void 0:Wf.enabled)!=null?Hf:!0,w=(Df=(Bf=o.launcher)==null?void 0:Bf.autoExpand)!=null?Df:!1,Le=(Nf=(Ff=o.features)==null?void 0:Ff.showReasoning)!=null?Nf:!0,He=(_f=(Of=o.features)==null?void 0:Of.showToolCalls)!=null?_f:!0,Me=(qf=(Uf=o.features)==null?void 0:Uf.scrollToBottom)!=null?qf:{};let Fe=Ft();oe=(zf=(Vf=o.features)==null?void 0:Vf.scrollBehavior)!=null?zf:{},Fe!==Ft()&&(ss(),bn()),dn(),qr();let Ne=ie;if(ie=(jf=($f=o.features)==null?void 0:$f.showEventStreamToggle)!=null?jf:!1,ie&&!Ne){if(j||(Te=new Us(ge),j=new _s(qe,Te),ee=ee!=null?ee:new qs,Te.open().then(()=>j==null?void 0:j.restore()).catch(()=>{}),q.setSSEEventCallback((Y,Mt)=>{var qt;(qt=o.onSSEEvent)==null||qt.call(o,Y,Mt),ee==null||ee.processEvent(Y,Mt),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(Mt)})})),!ht&&Ae){let Y=(Kf=(Gf=o.features)==null?void 0:Gf.eventStream)==null?void 0:Kf.classNames,Mt="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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");ht=v("button",Mt),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ir.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let qt=he("activity","18px","currentColor",1.5);qt&&ht.appendChild(qt);let at=je.clearChatButtonWrapper,kt=je.closeButtonWrapper,dr=at||kt;dr&&dr.parentNode===Ae?Ae.insertBefore(ht,dr):Ae.appendChild(ht),ht.addEventListener("click",()=>{te?uo():Vo()})}}else!ie&&Ne&&(uo(),ht&&(ht.remove(),ht=null),j==null||j.clear(),Te==null||Te.destroy(),j=null,Te=null,ee==null||ee.reset(),ee=null);if(((Xf=o.launcher)==null?void 0:Xf.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((Qf=o.launcher)==null?void 0:Qf.enabled)===!1&&ir&&(ir.remove(),ir=null),((Jf=o.launcher)==null?void 0:Jf.enabled)!==!1&&!Yt&&!ir){let{instance:Y,element:Mt}=xp({config:o,plugins:n,onToggle:xu});Yt=Y,Y||(ir=Mt),e.appendChild(Mt)}Yt&&Yt.update(o),ce&&((Yf=o.launcher)==null?void 0:Yf.title)!==void 0&&(ce.textContent=o.launcher.title),Se&&((Zf=o.launcher)==null?void 0:Zf.subtitle)!==void 0&&(Se.textContent=o.launcher.subtitle);let Ue=(em=o.layout)==null?void 0:em.header;if((Ue==null?void 0:Ue.layout)!==W&&Ae){let Y=Ue?Ga(o,Ue,{showClose:D(),onClose:()=>Ot(!1,"user")}):nn({config:o,showClose:D(),onClose:()=>Ot(!1,"user")});ct.replaceHeader(Y),Ae=ct.header.element,H=ct.header.iconHolder,ce=ct.header.headerTitle,Se=ct.header.headerSubtitle,Ve=ct.header.closeButton,W=Ue==null?void 0:Ue.layout}else if(Ue&&(H&&(H.style.display=Ue.showIcon===!1?"none":""),ce&&(ce.style.display=Ue.showTitle===!1?"none":""),Se&&(Se.style.display=Ue.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ue.showCloseButton===!1?"none":""),je.clearChatButtonWrapper)){let Y=Ue.showClearChat;if(Y!==void 0){je.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:Mt}=je;Mt&&!Mt.classList.contains("persona-absolute")&&(Y?Mt.classList.remove("persona-ml-auto"):Mt.classList.add("persona-ml-auto"))}}let ut=((tm=o.layout)==null?void 0:tm.showHeader)!==!1;Ae&&(Ae.style.display=ut?"":"none");let ot=((rm=o.layout)==null?void 0:rm.showFooter)!==!1;Ie&&(Ie.style.display=ot?"":"none"),Qr(),qr(),k!==M?k?Ot(w,"auto"):(O=!0,ps()):w!==S&&Ot(w,"auto"),S=w,M=k,us(),Tu();let $e=JSON.stringify(l.toolCall)!==JSON.stringify(f),Xe=JSON.stringify(o.messageActions)!==JSON.stringify(x),xt=JSON.stringify((om=o.layout)==null?void 0:om.messages)!==JSON.stringify(b),F=((nm=o.loadingIndicator)==null?void 0:nm.render)!==(B==null?void 0:B.render)||((am=o.loadingIndicator)==null?void 0:am.renderIdle)!==(B==null?void 0:B.renderIdle)||((sm=o.loadingIndicator)==null?void 0:sm.showBubble)!==(B==null?void 0:B.showBubble),Be=o.iterationDisplay!==V,Re=((lm=(im=o.features)==null?void 0:im.showReasoning)!=null?lm:!0)!==(U!=null?U:!0)||((cm=(dm=o.features)==null?void 0:dm.showToolCalls)!=null?cm:!0)!==(_!=null?_:!0)||JSON.stringify((pm=o.features)==null?void 0:pm.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify((um=o.features)==null?void 0:um.reasoningDisplay)!==JSON.stringify(re);($e||Xe||xt||F||Be||Re)&&q&&(Ca++,is(Ye,q.getMessages(),Z));let Pt=(mm=(fm=o.features)==null?void 0:fm.streamAnimation)==null?void 0:mm.type;if(Pt!==J&&Pt&&Pt!=="none"){let Y=ja(Pt,(hm=(gm=o.features)==null?void 0:gm.streamAnimation)==null?void 0:hm.plugins);Y&&Ji(Y,e)}let Oe=(xm=o.launcher)!=null?xm:{},Gt=(ym=Oe.headerIconHidden)!=null?ym:!1,wt=(vm=(bm=o.layout)==null?void 0:bm.header)==null?void 0:vm.showIcon,lr=Gt||wt===!1,Br=Oe.headerIconName,Ht=(wm=Oe.headerIconSize)!=null?wm:"48px";if(H){let Y=Ce.querySelector(".persona-border-b-persona-divider"),Mt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(lr)H.style.display="none",Y&&Mt&&!Y.contains(Mt)&&Y.insertBefore(Mt,Y.firstChild);else{if(H.style.display="",H.style.height=Ht,H.style.width=Ht,Y&&Mt&&(Y.contains(H)?H.nextSibling!==Mt&&(H.remove(),Y.insertBefore(H,Mt)):Y.insertBefore(H,Mt)),Br){let at=parseFloat(Ht)||24,kt=he(Br,at*.6,"currentColor",1);kt?H.replaceChildren(kt):H.textContent=(Cm=Oe.agentIconText)!=null?Cm:"\u{1F4AC}"}else if(Oe.iconUrl){let at=H.querySelector("img");if(at)at.src=Oe.iconUrl,at.style.height=Ht,at.style.width=Ht;else{let kt=document.createElement("img");kt.src=Oe.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Ht,kt.style.width=Ht,H.replaceChildren(kt)}}else{let at=H.querySelector("svg"),kt=H.querySelector("img");(at||kt)&&H.replaceChildren(),H.textContent=(Sm=Oe.agentIconText)!=null?Sm:"\u{1F4AC}"}let qt=H.querySelector("img");qt&&(qt.style.height=Ht,qt.style.width=Ht)}}let hr=(Mm=(Am=o.layout)==null?void 0:Am.header)==null?void 0:Mm.showTitle,Vr=(Em=(Tm=o.layout)==null?void 0:Tm.header)==null?void 0:Em.showSubtitle;if(ce&&(ce.style.display=hr===!1?"none":""),Se&&(Se.style.display=Vr===!1?"none":""),Ve){((Lm=(km=o.layout)==null?void 0:km.header)==null?void 0:Lm.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let Mt=(Pm=Oe.closeButtonSize)!=null?Pm:"32px",qt=(Rm=Oe.closeButtonPlacement)!=null?Rm:"inline";Ve.style.height=Mt,Ve.style.width=Mt;let{closeButtonWrapper:at}=je,kt=qt==="top-right",dr=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==dr)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(at);else{let dt=(Wm=(Im=Oe.clearChat)==null?void 0:Im.placement)!=null?Wm:"inline",cr=(Bm=(Hm=Oe.clearChat)==null?void 0:Hm.enabled)!=null?Bm:!0;at.className=cr&&dt==="inline"?"":"persona-ml-auto";let Dr=Ce.querySelector(".persona-border-b-persona-divider");Dr&&Dr.appendChild(at)}if(Ve.style.color=Oe.closeButtonColor||Ir.actionIconColor,Oe.closeButtonBackgroundColor?(Ve.style.backgroundColor=Oe.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),Oe.closeButtonBorderWidth||Oe.closeButtonBorderColor){let dt=Oe.closeButtonBorderWidth||"0px",cr=Oe.closeButtonBorderColor||"transparent";Ve.style.border=`${dt} solid ${cr}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");Oe.closeButtonBorderRadius?(Ve.style.borderRadius=Oe.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),Oe.closeButtonPaddingX?(Ve.style.paddingLeft=Oe.closeButtonPaddingX,Ve.style.paddingRight=Oe.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Oe.closeButtonPaddingY?(Ve.style.paddingTop=Oe.closeButtonPaddingY,Ve.style.paddingBottom=Oe.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Cr=(Dm=Oe.closeButtonIconName)!=null?Dm:"x",ho=(Fm=Oe.closeButtonIconText)!=null?Fm:"\xD7";Ve.innerHTML="";let Pr=he(Cr,"28px","currentColor",1);Pr?Ve.appendChild(Pr):Ve.textContent=ho;let Jt=(Nm=Oe.closeButtonTooltipText)!=null?Nm:"Close chat",jr=(Om=Oe.closeButtonShowTooltip)!=null?Om:!0;if(Ve.setAttribute("aria-label",Jt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),jr&&Jt)){let dt=null,cr=()=>{if(dt||!Ve)return;let ra=Ve.ownerDocument,ms=ra.body;if(!ms)return;dt=No(ra,"div","persona-clear-chat-tooltip"),dt.textContent=Jt;let gs=No(ra,"div");gs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(gs);let oa=Ve.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Fn),dt.style.left=`${oa.left+oa.width/2}px`,dt.style.top=`${oa.top-8}px`,dt.style.transform="translate(-50%, -100%)",ms.appendChild(dt)},Dr=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cr),at.addEventListener("mouseleave",Dr),Ve.addEventListener("focus",cr),Ve.addEventListener("blur",Dr),at._cleanupTooltip=()=>{Dr(),at&&(at.removeEventListener("mouseenter",cr),at.removeEventListener("mouseleave",Dr)),Ve&&(Ve.removeEventListener("focus",cr),Ve.removeEventListener("blur",Dr))}}}let{clearChatButton:Ge,clearChatButtonWrapper:Rt}=je;if(Ge){let Y=(_m=Oe.clearChat)!=null?_m:{},Mt=(Um=Y.enabled)!=null?Um:!0,qt=(Vm=(qm=o.layout)==null?void 0:qm.header)==null?void 0:Vm.showClearChat,at=qt!==void 0?qt:Mt,kt=(zm=Y.placement)!=null?zm:"inline";if(Rt){Rt.style.display=at?"":"none";let{closeButtonWrapper:dr}=je;!R()&&dr&&!dr.classList.contains("persona-absolute")&&(at?dr.classList.remove("persona-ml-auto"):dr.classList.add("persona-ml-auto"));let Cr=kt==="top-right",ho=Rt.classList.contains("persona-absolute");if(!R()&&Cr!==ho&&at){if(Rt.remove(),Cr)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Ce.style.position="relative",Ce.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Jt=Ce.querySelector(".persona-border-b-persona-divider"),jr=je.closeButtonWrapper;Jt&&jr&&jr.parentElement===Jt?Jt.insertBefore(Rt,jr):Jt&&Jt.appendChild(Rt)}let Pr=je.closeButtonWrapper;Pr&&!Pr.classList.contains("persona-absolute")&&(Cr?Pr.classList.add("persona-ml-auto"):Pr.classList.remove("persona-ml-auto"))}}if(at){if(!R()){let dt=($m=Y.size)!=null?$m:"32px";Ge.style.height=dt,Ge.style.width=dt}let dr=(jm=Y.iconName)!=null?jm:"refresh-cw",Cr=(Gm=Y.iconColor)!=null?Gm:"";Ge.style.color=Cr||Ir.actionIconColor,Ge.innerHTML="";let ho=R()?"14px":"20px",Pr=he(dr,ho,"currentColor",2);if(Pr&&Ge.appendChild(Pr),Y.backgroundColor?(Ge.style.backgroundColor=Y.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let dt=Y.borderWidth||"0px",cr=Y.borderColor||"transparent";Ge.style.border=`${dt} solid ${cr}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");Y.borderRadius?(Ge.style.borderRadius=Y.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),Y.paddingX?(Ge.style.paddingLeft=Y.paddingX,Ge.style.paddingRight=Y.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Y.paddingY?(Ge.style.paddingTop=Y.paddingY,Ge.style.paddingBottom=Y.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Jt=(Km=Y.tooltipText)!=null?Km:"Clear chat",jr=(Xm=Y.showTooltip)!=null?Xm:!0;if(Ge.setAttribute("aria-label",Jt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),jr&&Jt)){let dt=null,cr=()=>{if(dt||!Ge)return;let ra=Ge.ownerDocument,ms=ra.body;if(!ms)return;dt=No(ra,"div","persona-clear-chat-tooltip"),dt.textContent=Jt;let gs=No(ra,"div");gs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(gs);let oa=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Fn),dt.style.left=`${oa.left+oa.width/2}px`,dt.style.top=`${oa.top-8}px`,dt.style.transform="translate(-50%, -100%)",ms.appendChild(dt)},Dr=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};Rt.addEventListener("mouseenter",cr),Rt.addEventListener("mouseleave",Dr),Ge.addEventListener("focus",cr),Ge.addEventListener("blur",Dr),Rt._cleanupTooltip=()=>{Dr(),Rt&&(Rt.removeEventListener("mouseenter",cr),Rt.removeEventListener("mouseleave",Dr)),Ge&&(Ge.removeEventListener("focus",cr),Ge.removeEventListener("blur",Dr))}}}}let zr=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zs],Qn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ya.message,ya.messageAndClick];A=$s({parsers:zr,handlers:Qn,getSessionMetadata:h,updateSessionMetadata:y,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Gx(o,A,ue),q.updateConfig(o),is(Ye,q.getMessages(),Z),wa(),au(),Tl(q.isStreaming());let Jn=((Qm=o.voiceRecognition)==null?void 0:Qm.enabled)===!0,Yn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Zn=((Ym=(Jm=o.voiceRecognition)==null?void 0:Jm.provider)==null?void 0:Ym.type)==="runtype";if(Jn&&(Yn||Zn))if(!N||!ye){let Y=Xy(o.voiceRecognition,o.sendButton);Y&&(N=Y.micButton,ye=Y.micButtonWrapper,gt.insertBefore(ye,Ar),N.addEventListener("click",ei),N.disabled=q.isStreaming())}else{let Y=(Zm=o.voiceRecognition)!=null?Zm:{},Mt=(eg=o.sendButton)!=null?eg:{},qt=(tg=Y.iconName)!=null?tg:"mic",at=(rg=Mt.size)!=null?rg:"40px",kt=(og=Y.iconSize)!=null?og:at,dr=parseFloat(kt)||24;N.style.width=kt,N.style.height=kt,N.style.minWidth=kt,N.style.minHeight=kt;let Cr=(ag=(ng=Y.iconColor)!=null?ng:Mt.textColor)!=null?ag:"currentColor";N.innerHTML="";let ho=he(qt,dr,Cr,2);ho?N.appendChild(ho):N.textContent="\u{1F3A4}";let Pr=(sg=Y.backgroundColor)!=null?sg:Mt.backgroundColor;Pr?N.style.backgroundColor=Pr:N.style.backgroundColor="",Cr?N.style.color=Cr:N.style.color="var(--persona-text, #111827)",Y.borderWidth?(N.style.borderWidth=Y.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),Y.borderColor?N.style.borderColor=Y.borderColor:N.style.borderColor="",Y.paddingX?(N.style.paddingLeft=Y.paddingX,N.style.paddingRight=Y.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),Y.paddingY?(N.style.paddingTop=Y.paddingY,N.style.paddingBottom=Y.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let Jt=ye==null?void 0:ye.querySelector(".persona-send-button-tooltip"),jr=(ig=Y.tooltipText)!=null?ig:"Start voice recognition";if(((lg=Y.showTooltip)!=null?lg:!1)&&jr)if(Jt)Jt.textContent=jr,Jt.style.display="";else{let cr=document.createElement("div");cr.className="persona-send-button-tooltip",cr.textContent=jr,ye==null||ye.insertBefore(cr,N)}else Jt&&(Jt.style.display="none");ye.style.display="",N.disabled=q.isStreaming()}else N&&ye&&(ye.style.display="none",((cg=(dg=o.voiceRecognition)==null?void 0:dg.provider)==null?void 0:cg.type)==="runtype"?q.isVoiceActive()&&q.toggleVoice():Bo&&wn());if(((pg=o.attachments)==null?void 0:pg.enabled)===!0)if(!mt||!ae){let Y=(ug=o.attachments)!=null?ug:{},qt=(mg=((fg=o.sendButton)!=null?fg:{}).size)!=null?mg:"40px";Lt||(Lt=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,xe)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((gg=Y.allowedTypes)!=null?gg:on).join(","),Ke.multiple=((hg=Y.maxFiles)!=null?hg:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Ct.insertBefore(Ke,xe)),mt=v("div","persona-send-button-wrapper"),ae=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ae.type="button",ae.setAttribute("aria-label",(xg=Y.buttonTooltipText)!=null?xg:"Attach file");let at=(yg=Y.buttonIconName)!=null?yg:"paperclip",kt=qt,dr=parseFloat(kt)||40,Cr=Math.round(dr*.6);ae.style.width=kt,ae.style.height=kt,ae.style.minWidth=kt,ae.style.minHeight=kt,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.style.backgroundColor="transparent",ae.style.color="var(--persona-primary, #111827)",ae.style.border="none",ae.style.borderRadius="6px",ae.style.transition="background-color 0.15s ease",ae.addEventListener("mouseenter",()=>{ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ae.addEventListener("mouseleave",()=>{ae.style.backgroundColor="transparent"});let ho=he(at,Cr,"currentColor",1.5);ho?ae.appendChild(ho):ae.textContent="\u{1F4CE}",ae.addEventListener("click",jr=>{jr.preventDefault(),Ke==null||Ke.click()}),mt.appendChild(ae);let Pr=(bg=Y.buttonTooltipText)!=null?bg:"Attach file",Jt=v("div","persona-send-button-tooltip");Jt.textContent=Pr,mt.appendChild(Jt),Qe.append(mt),!St&&Ke&&Lt&&(St=pa.fromConfig(Y),St.setPreviewsContainer(Lt),Ke.addEventListener("change",async()=>{St&&(Ke!=null&&Ke.files)&&(await St.handleFileSelect(Ke.files),Ke.value="")})),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(Kx(Y.dropOverlay))}else{mt.style.display="";let Y=(vg=o.attachments)!=null?vg:{};Ke&&(Ke.accept=((wg=Y.allowedTypes)!=null?wg:on).join(","),Ke.multiple=((Cg=Y.maxFiles)!=null?Cg:4)>1),St&&St.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else mt&&(mt.style.display="none"),St&&St.clearAttachments(),(Sg=Ce.querySelector(".persona-attachment-drop-overlay"))==null||Sg.remove();let Xt=(Ag=o.sendButton)!=null?Ag:{},ea=(Mg=Xt.useIcon)!=null?Mg:!1,Sn=(Tg=Xt.iconText)!=null?Tg:"\u2191",An=Xt.iconName,Zo=(Eg=Xt.tooltipText)!=null?Eg:"Send message",ta=(kg=Xt.showTooltip)!=null?kg:!1,Ze=(Lg=Xt.size)!=null?Lg:"40px",Dt=Xt.backgroundColor,Bt=Xt.textColor;if(ea){if(de.style.width=Ze,de.style.height=Ze,de.style.minWidth=Ze,de.style.minHeight=Ze,de.style.fontSize="18px",de.style.lineHeight="1",de.innerHTML="",Bt?de.style.color=Bt:de.style.color="var(--persona-button-primary-fg, #ffffff)",An){let Y=parseFloat(Ze)||24,Mt=(Bt==null?void 0:Bt.trim())||"currentColor",qt=he(An,Y,Mt,2);qt?de.appendChild(qt):de.textContent=Sn}else de.textContent=Sn;de.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Dt?(de.style.backgroundColor=Dt,de.classList.remove("persona-bg-persona-primary")):(de.style.backgroundColor="",de.classList.add("persona-bg-persona-primary"))}else de.textContent=(Rg=(Pg=o.copy)==null?void 0:Pg.sendButtonLabel)!=null?Rg:"Send",de.style.width="",de.style.height="",de.style.minWidth="",de.style.minHeight="",de.style.fontSize="",de.style.lineHeight="",de.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",Dt?(de.style.backgroundColor=Dt,de.classList.remove("persona-bg-persona-accent")):de.classList.add("persona-bg-persona-accent"),Bt?de.style.color=Bt:de.classList.add("persona-text-white");Xt.borderWidth?(de.style.borderWidth=Xt.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),Xt.borderColor?de.style.borderColor=Xt.borderColor:de.style.borderColor="",Xt.paddingX?(de.style.paddingLeft=Xt.paddingX,de.style.paddingRight=Xt.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Xt.paddingY?(de.style.paddingTop=Xt.paddingY,de.style.paddingBottom=Xt.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let $t=Ar==null?void 0:Ar.querySelector(".persona-send-button-tooltip");if(ta&&Zo)if($t)$t.textContent=Zo,$t.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Zo,Ar==null||Ar.insertBefore(Y,de)}else $t&&($t.style.display="none");let _t=(Dg=(Ig=o.layout)==null?void 0:Ig.contentMaxWidth)!=null?Dg:R()?(Bg=(Hg=(Wg=o.launcher)==null?void 0:Wg.composerBar)==null?void 0:Hg.contentMaxWidth)!=null?Bg:"720px":void 0;_t?(Ye.style.maxWidth=_t,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Ct&&(Ct.style.maxWidth=_t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Vt&&(Vt.style.maxWidth=_t,Vt.style.marginLeft="auto",Vt.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),Vt&&(Vt.style.maxWidth="",Vt.style.marginLeft="",Vt.style.marginRight=""));let ft=(Fg=o.statusIndicator)!=null?Fg:{},Ut=(Ng=ft.visible)!=null?Ng:!0;if(br.style.display=Ut?"":"none",q){let Y=q.getStatus();jt(br,(qt=>{var at,kt,dr,Cr;return qt==="idle"?(at=ft.idleText)!=null?at:rr.idle:qt==="connecting"?(kt=ft.connectingText)!=null?kt:rr.connecting:qt==="connected"?(dr=ft.connectedText)!=null?dr:rr.connected:qt==="error"?(Cr=ft.errorText)!=null?Cr:rr.error:rr[qt]})(Y),ft,Y)}br.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xr=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";br.classList.add(xr)},open(){D()&&Ot(!0,"api")},close(){D()&&Ot(!1,"api")},toggle(){D()&&Ot(!O,"api")},reconnect(){q.reconnectNow()},clearChat(){Mr=!1,q.clearMessages(),Ro.clear(),bn();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d!=null&&d.clear&&Xo(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},A.syncFromMetadata(),j==null||j.clear(),ee==null||ee.reset(),Ee==null||Ee.update()},setMessage(l){return!xe||q.isStreaming()?!1:(!O&&D()&&Ot(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(q.isStreaming())return!1;let f=(l==null?void 0:l.trim())||xe.value.trim();return f?(!O&&D()&&Ot(!0,"system"),xe.value="",xe.style.height="auto",q.sendMessage(f),!0):!1},startVoiceRecognition(){var f,x;return q.isStreaming()?!1:((x=(f=o.voiceRecognition)==null?void 0:f.provider)==null?void 0:x.type)==="runtype"?(q.isVoiceActive()||(!O&&D()&&Ot(!0,"system"),G.manuallyDeactivated=!1,lt(),q.toggleVoice().then(()=>{G.active=q.isVoiceActive(),tt("user"),q.isVoiceActive()&&ka()})),!0):Bo?!0:hu()?(!O&&D()&&Ot(!0,"system"),G.manuallyDeactivated=!1,lt(),Ys("user"),!0):!1},stopVoiceRecognition(){var l,f;return((f=(l=o.voiceRecognition)==null?void 0:l.provider)==null?void 0:f.type)==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,lt(),tt("user"),Yo()}),!0):!1:Bo?(G.manuallyDeactivated=!0,lt(),wn("user"),!0):!1},injectMessage(l){return!O&&D()&&Ot(!0,"system"),q.injectMessage(l)},injectAssistantMessage(l){!O&&D()&&Ot(!0,"system");let f=q.injectAssistantMessage(l);return Q&&(Q=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),f},injectUserMessage(l){return!O&&D()&&Ot(!0,"system"),q.injectUserMessage(l)},injectSystemMessage(l){return!O&&D()&&Ot(!0,"system"),q.injectSystemMessage(l)},injectMessageBatch(l){return!O&&D()&&Ot(!0,"system"),q.injectMessageBatch(l)},injectComponentDirective(l){return!O&&D()&&Ot(!0,"system"),q.injectComponentDirective(l)},injectTestMessage(l){!O&&D()&&Ot(!0,"system"),q.injectTestEvent(l)},async connectStream(l,f){return q.connectStream(l,f)},__pushEventStreamEvent(l){j&&(ee==null||ee.processEvent(l.type,l.payload),j.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ie||!j||Vo()},hideEventStream(){te&&uo()},isEventStreamVisible(){return te},showArtifacts(){so(o)&&(Mr=!1,ko(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){so(o)&&(Mr=!0,ko())},upsertArtifact(l){return so(o)?(Mr=!1,q.upsertArtifact(l)):null},selectArtifact(l){so(o)&&q.selectArtifact(l)},clearArtifacts(){so(o)&&q.clearArtifacts()},getArtifacts(){var l;return(l=q==null?void 0:q.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=q==null?void 0:q.getSelectedArtifactId())!=null?l:null},focusInput(){return k&&!O&&!R()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,f,x){let P=q.getMessages().find(B=>{var V;return B.variant==="approval"&&((V=B.approval)==null?void 0:V.id)===l});if(!(P!=null&&P.approval))throw new Error(`Approval not found: ${l}`);if(P.approval.toolType==="webmcp"){q.resolveWebMcpApproval(P.id,f);return}return q.resolveApproval(P.approval,f,x)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){y(l)},on(l,f){return i.on(l,f)},off(l,f){i.off(l,f)},isOpen(){return D()&&O},isVoiceActive(){return G.active},toggleReadAloud(l){q.toggleReadAloud(l)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(l){return q.getReadAloudState(l)},onReadAloudChange(l){return q.onReadAloudChange(l)},getState(){return{open:D()&&O,launcherEnabled:k,voiceActive:G.active,streaming:q.isStreaming()}},showCSATFeedback(l){!O&&D()&&Ot(!0,"system");let f=Ye.querySelector(".persona-feedback-container");f&&f.remove();let x=xl({onSubmit:async(b,P)=>{var B;q.isClientTokenMode()&&await q.submitCSATFeedback(b,P),(B=l==null?void 0:l.onSubmit)==null||B.call(l,b,P)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!O&&D()&&Ot(!0,"system");let f=Ye.querySelector(".persona-feedback-container");f&&f.remove();let x=yl({onSubmit:async(b,P)=>{var B;q.isClientTokenMode()&&await q.submitNPSFeedback(b,P),(B=l==null?void 0:l.onSubmit)==null||B.call(l,b,P)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return q.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return q.submitNPSFeedback(l,f)},destroy(){Pl(),Xn!=null&&(clearInterval(Xn),Xn=null),it.forEach(l=>l()),fe.remove(),st==null||st.remove(),Yt==null||Yt.destroy(),ir==null||ir.remove(),Po&&Ve.removeEventListener("click",Po)}};if((((Tf=r==null?void 0:r.debugTools)!=null?Tf:!1)||!!o.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,f={controller:tr,getMessages:tr.getMessages,getStatus:tr.getStatus,getMetadata:tr.getPersistentMetadata,updateMetadata:tr.updatePersistentMetadata,clearHistory:()=>tr.clearChat(),setVoiceActive:x=>x?tr.startVoiceRecognition():tr.stopVoiceRecognition()};window.AgentWidgetBrowser=f,it.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&tr.focusInput()};if(window.addEventListener("persona:focusInput",f),it.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let U=ne=>{let re=ne.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&tr.showEventStream()},_=ne=>{let re=ne.detail;(!(re!=null&&re.instanceId)||re.instanceId===l)&&tr.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",_),it.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",_)})}let x=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&tr.showArtifacts()},b=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&tr.hideArtifacts()},P=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==l||_!=null&&_.artifact&&tr.upsertArtifact(_.artifact)},B=U=>{let _=U.detail;_!=null&&_.instanceId&&_.instanceId!==l||typeof(_==null?void 0:_.id)=="string"&&tr.selectArtifact(_.id)},V=U=>{let _=U.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&tr.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",P),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",V),it.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",P),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",V)})}let oo=Z0(o.persistState);if(oo&&D()){let l=ew(oo.storage),f=`${oo.keyPrefix}widget-open`,x=`${oo.keyPrefix}widget-voice`,b=`${oo.keyPrefix}widget-voice-mode`;if(l){let P=((Ef=oo.persist)==null?void 0:Ef.openState)&&l.getItem(f)==="true",B=((kf=oo.persist)==null?void 0:kf.voiceState)&&l.getItem(x)==="true",V=((Lf=oo.persist)==null?void 0:Lf.voiceState)&&l.getItem(b)==="true";if(P&&setTimeout(()=>{tr.open(),setTimeout(()=>{var U;if(B||V)tr.startVoiceRecognition();else if((U=oo.persist)!=null&&U.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(Pf=oo.persist)!=null&&Pf.openState&&(i.on("widget:opened",()=>{l.setItem(f,"true")}),i.on("widget:closed",()=>{l.setItem(f,"false")})),(Rf=oo.persist)!=null&&Rf.voiceState&&(i.on("voice:state",U=>{l.setItem(x,U.active?"true":"false")}),i.on("user:message",U=>{l.setItem(b,U.viaVoice?"true":"false")})),oo.clearOnChatClear){let U=()=>{l.removeItem(f),l.removeItem(x),l.removeItem(b)},_=()=>U();window.addEventListener("persona:clear-chat",_),it.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return g&&D()&&setTimeout(()=>{tr.open()},0),Ma(),Xs||oi().then(()=>{q&&(Ca++,Ro.clear(),is(Ye,q.getMessages(),Z))}).catch(()=>{}),tr};var tw=(e,t)=>{let r=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(r);if(o)return Math.max(0,parseFloat(o[1]));let n=/^(\d+(?:\.\d+)?)%$/i.exec(r);return n?Math.max(0,t*parseFloat(n[1])/100):420},rw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ow=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},nw=(e,t)=>{let r=e.parentElement;if(!r)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",r.appendChild(o);let n=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!n||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.")},Xx=(e,t)=>{var o,n;let r=(n=(o=t==null?void 0:t.launcher)==null?void 0:o.enabled)!=null?n:!0;e.className="persona-host",e.style.height=r?"":"100%",e.style.display=r?"":"flex",e.style.flexDirection=r?"":"column",e.style.flex=r?"":"1 1 auto",e.style.minHeight=r?"":"0"},Dp=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=""},Qx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Dp(e)},Wp=e=>{e.style.transition=""},Hp=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=""},Bp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},wl=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},aw=(e,t,r,o,n)=>{n?r.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(r,o),e.appendChild(t)):r.parentElement===t&&(t.replaceChildren(),e.appendChild(r),e.appendChild(o))},sw=(e,t,r,o,n,a)=>{let s=a?t:e;n==="left"?s.firstElementChild!==o&&s.replaceChildren(o,r):s.lastElementChild!==o&&s.replaceChildren(r,o)},Jx=(e,t,r,o,n,a,s)=>{var h,y,E,T,A,k;let i=Kr(a),c=i.reveal==="push";aw(e,t,r,o,c),sw(e,t,r,o,i.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.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",r.style.display="flex",r.style.flexDirection="column",r.style.minHeight="0",r.style.position="relative",n.className="persona-host",n.style.height="100%",n.style.minHeight="0",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto";let d=e.ownerDocument.defaultView,p=(y=(h=a==null?void 0:a.launcher)==null?void 0:h.mobileFullscreen)!=null?y:!0,m=(T=(E=a==null?void 0:a.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,g=d!=null?d.innerWidth<=m:!1;if(p&&g&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Hp(t),Wp(o),Qx(o),Bp(r),wl(n,o),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",r.style.flex="1 1 auto",r.style.width="100%",r.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((k=(A=a==null?void 0:a.launcher)==null?void 0:A.zIndex)!=null?k:Sr),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",r.style.flex="1 1 auto",r.style.width="100%",r.style.maxWidth="100%",r.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Qx(o),rw(o,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Hp(t),Wp(o),Bp(r),wl(n,o);let w=i.animate?"transform 180ms ease":"none",C=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=s?"translateX(0)":C;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=i.width,o.style.maxWidth=i.width,o.style.minWidth=i.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=w,o.style.transform=S,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",i.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Wp(o),Dp(o),wl(n,o);let w=tw(i.width,e.clientWidth),C=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",M=i.side==="right"?s?-w:0:s?0:-w;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=`${C+w}px`,t.style.transition=S,t.style.marginLeft=`${M}px`,t.style.transform="",r.style.flex="0 0 auto",r.style.flexGrow="0",r.style.flexShrink="0",r.style.width=`${C}px`,r.style.maxWidth=`${C}px`,r.style.minWidth=`${C}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.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="",Hp(t),Dp(o),Bp(r),wl(n,o);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let C=s?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",M=!s;o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${C}`,o.style.width=C,o.style.maxWidth=C,o.style.minWidth=C,o.style.minHeight="0",ow(o,i.maxHeight),o.style.overflow=w||M?"hidden":"visible",o.style.transition=S,w&&(o.style.alignItems=i.side==="right"?"flex-start":"flex-end",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.boxSizing="border-box")}},iw=(e,t)=>{let r=e.ownerDocument.createElement("div");return Xx(r,t),e.appendChild(r),{mode:"direct",host:r,shell:null,syncWidgetState:()=>{},updateConfig(o){Xx(r,o)},destroy(){r.remove()}}},lw=(e,t)=>{var k,w,C,S;let{ownerDocument:r}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let n=e.tagName.toUpperCase();if(n==="BODY"||n==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=r.createElement("div"),i=r.createElement("div"),c=r.createElement("div"),d=r.createElement("aside"),p=r.createElement("div"),m=(w=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||w?(S=(C=t==null?void 0:t.launcher)==null?void 0:C.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",d.appendChild(p),o.insertBefore(s,e),c.appendChild(e);let g=null,u=()=>{g==null||g.disconnect(),g=null},h=()=>{u(),Kr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Jx(s,i,c,d,p,t,m)}),g.observe(s))},y=!1,E=()=>{Jx(s,i,c,d,p,t,m),h(),m&&!y&&s.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,nw(s,Kr(t)))},T=s.ownerDocument.defaultView,A=()=>{E()};return T==null||T.addEventListener("resize",A),Kr(t).reveal==="push"?(i.appendChild(c),i.appendChild(d),s.appendChild(i)):(s.appendChild(c),s.appendChild(d)),E(),{mode:"docked",host:p,shell:s,syncWidgetState(M){let W=M.launcherEnabled?M.open:!0;m!==W&&(m=W,E())},updateConfig(M){var W,I;t=M,((I=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?I:!0)===!1&&(m=!0),E()},destroy(){T==null||T.removeEventListener("resize",A),u(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Gs=(e,t)=>or(t)?lw(e,t):iw(e,t);var Fp={},dw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},cw=()=>{try{if(typeof Fp!="undefined"&&Fp.url)return new URL("../widget.css",Fp.url).href}catch{}return null},Yx=(e,t)=>{let r=cw(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let a=n.cloneNode(!0);e.insertBefore(a,e.firstChild)};if(e instanceof ShadowRoot)if(r){let n=t.createElement("link");n.rel="stylesheet",n.href=r,n.setAttribute("data-persona","true"),e.insertBefore(n,e.firstChild)}else o();else if(!t.head.querySelector("link[data-persona]")&&r){let a=t.createElement("link");a.rel="stylesheet",a.href=r,a.setAttribute("data-persona","true"),t.head.appendChild(a)}},Zx=e=>{var E;let t=dw(e.target),r=e.useShadowDom===!0,o=t.ownerDocument,n=e.config,a=Gs(t,n),s,i=[],c=(T,A)=>{var S,M;let w=!((M=(S=A==null?void 0:A.launcher)==null?void 0:S.enabled)!=null?M:!0)||or(A),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),w&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0"),r){let W=T.attachShadow({mode:"open"});W.appendChild(C),Yx(W,o)}else T.appendChild(C),Yx(T,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},d=()=>{a.syncWidgetState(s.getState())},p=()=>{i.forEach(T=>T()),i=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},m=()=>{let T=c(a.host,n);s=vl(T,n,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(T=>T()),i=[],s.destroy()};m(),(E=e.onChatReady)==null||E.call(e);let u=T=>{g(),a.destroy(),a=Gs(t,T),n=T,m()},h={update(T){var M,W,I,R,D,O;let A={...n,...T,launcher:{...(M=n==null?void 0:n.launcher)!=null?M:{},...(W=T==null?void 0:T.launcher)!=null?W:{},dock:{...(R=(I=n==null?void 0:n.launcher)==null?void 0:I.dock)!=null?R:{},...(O=(D=T==null?void 0:T.launcher)==null?void 0:D.dock)!=null?O:{}}}},k=or(n),w=or(A),C=On(n),S=On(A);if(k!==w||C!==S){u(A);return}n=A,a.updateConfig(n),s.update(T),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(h,{get(T,A,k){if(A==="host")return a.host;if(A in T)return Reflect.get(T,A,k);let w=s[A];return typeof w=="function"?w.bind(s):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var ny=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),pw=new Set(["button","a","input","select","textarea","details","summary"]),uw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Np=/\b(product|card|item|listing|result)\b/i,_p=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,fw=3e3,mw=100;function ay(e){let t=typeof e.className=="string"?e.className:"";if(Np.test(t)||e.id&&Np.test(e.id))return!0;for(let r=0;r<e.attributes.length;r++){let o=e.attributes[r];if(o.name.startsWith("data-")&&Np.test(o.value))return!0}return!1}function sy(e){var t;return _p.test(((t=e.textContent)!=null?t:"").trim())}function iy(e){var r;let t=e.querySelectorAll("a[href]");for(let o=0;o<t.length;o++){let n=(r=t[o].getAttribute("href"))!=null?r:"";if(n&&n!=="#"&&!n.toLowerCase().startsWith("javascript:"))return!0}return!1}function gw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ey(e){let t=e.match(_p);return t?t[0]:null}function ty(e){var o,n,a;let t=(o=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?o:e.querySelector("a[href]");if(t&&((n=t.textContent)!=null&&n.trim())){let s=t.getAttribute("href");return{title:t.textContent.trim(),href:s&&s!=="#"?s:null}}let r=e.querySelector("h1, h2, h3, h4, h5, h6");return(a=r==null?void 0:r.textContent)!=null&&a.trim()?{title:r.textContent.trim(),href:null}:{title:"",href:null}}function hw(e){let t=[],r=o=>{let n=o.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll("button").forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('[role="button"]').forEach(o=>{var n;return r((n=o.textContent)!=null?n:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{var n;r((n=o.value)!=null?n:"")}),t.slice(0,6)}var xw="commerce-card",yw="result-card";function ry(e){return!ay(e)||!sy(e)||!iy(e)&&!gw(e)?0:5200}function oy(e){var o;return!ay(e)||sy(e)||!iy(e)||((o=e.textContent)!=null?o:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Up=[{id:xw,scoreElement(e){return ry(e)},shouldSuppressDescendant(e,t,r){if(t===e||!e.contains(t))return!1;if(r.interactivity==="static"){let o=r.text.trim();return!!(o.length===0||_p.test(o)&&o.length<32)}return!0},formatSummary(e,t){var c,d,p;if(ry(e)===0)return null;let{title:r,href:o}=ty(e),n=(p=(d=ey(((c=e.textContent)!=null?c:"").trim()))!=null?d:ey(t.text))!=null?p:"",a=hw(e);return[o&&r?`[${r}](${o})${n?`: ${n}`:""}`:r?`${r}${n?`: ${n}`:""}`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
113
|
-
`)}},{id:yw,scoreElement(e){return oy(e)},formatSummary(e,t){if(oy(e)===0)return null;let{title:r,href:o}=ty(e);return[o&&r?`[${r}](${o})`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
114
|
-
`)}}
|
|
115
|
-
${s.map(
|
|
142
|
+
${rt?"background: transparent !important;":""}
|
|
143
|
+
`}if(!v&&!i){let Rt="max-height: -moz-available !important; max-height: stretch !important;",tn=m?"":"padding-top: 1.25em !important;",Ls=m?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;Me.style.cssText+=Rt+tn+Ls}zo()};hs(),or(e,o),Za(e,o),es(e,o),ta=()=>{hs(),or(e,o),Za(e,o),es(e,o),ds?e.style.setProperty("--persona-artifact-welded-outer-radius",ds):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let je=[];je.push(()=>{document.removeEventListener("keydown",vu)}),je.push(()=>{Yr!==null&&clearTimeout(Yr)});let Pn=null,Rn=null;je.push(()=>{Pn?.(),Pn=null,Rn?.(),Rn=null}),ea&&je.push(()=>{ea?.disconnect(),ea=null}),je.push(()=>{ra?.(),ra=null,gl(),vt&&(vt.remove(),vt=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),Z&&je.push(()=>{Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),qe?.destroy(),qe=null,Oe?.destroy(),Oe=null,xe=null});let Do=null,Au=()=>{Do&&(Do(),Do=null),o.colorScheme==="auto"&&(Do=Dr(()=>{or(e,o)}))};Au(),je.push(()=>{Do&&(Do(),Do=null)}),je.push(s);let ys=o.features?.streamAnimation;if(ys?.type&&ys.type!=="none"){let i=Ur(ys.type,ys.plugins);i&&(Ni(i,e),je.push(()=>cg(e)))}let xs=Rg(bt),Fo=null,z,hl=i=>{if(!z)return;let m=i??z.getMessages(),x=o.features?.suggestReplies?.enabled!==!1?zs(m):null;x?xs.render(x,z,q,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?xs.render([],z,q,m):xs.render(o.suggestionChips,z,q,m,o.suggestionChipsConfig)},Cn=!1,No=tg(),hr=new Map,Oo=new Map,no=new Map,yl=0,qh=zn()!==null,an=Ii(),mn=0,oo=null,gn=!1,bs=!1,ro=0,wn=null,_o=null,xl=!1,vs=!1,bl=null,aa=!0,vl=!1,Cl=null,Vh=4,Cs=24,zh=80,wl=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Su=o.voiceRecognition?.autoResume??!1,_n=i=>{l.emit("voice:state",{active:Je.active,source:i,timestamp:Date.now()})},An=()=>{S(i=>({...i,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},$h=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Vp(d.voiceState),m=!!i.active,x=Number(i.timestamp??0);Je.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-x<uC&&setTimeout(()=>{Je.active||(Je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Je.active=z.isVoiceActive(),_n("restore"),z.isVoiceActive()&&Cr()}):Ss("restore"))},1e3)},jh=()=>z?Kg(z.getMessages()).filter(i=>!i.__skipPersist):[],ws=null,Mu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Al=(i,m)=>{let x=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(V=>{Mu(m,V)})}catch(Q){return Mu(m,Q),null}},v=ws,L=v?v.then(()=>x()??void 0):x();if(!L)return;let H=L.finally(()=>{ws===H&&(ws=null)});ws=H};function Sl(i){if(!c?.save)return;let x={messages:i?Kg(i):z?jh():[],metadata:d,artifacts:bn.artifacts,selectedArtifactId:bn.selectedId};Al(()=>c.save(x),"[AgentWidget] Failed to persist state:")}let yr=null,Tu=()=>Me.querySelector("#persona-scroll-container")||ie,sa=()=>{yr!==null&&(cancelAnimationFrame(yr),yr=null),gn=!1},Eu=()=>{oo!==null&&(cancelAnimationFrame(oo),oo=null),bs=!1,sa()},Gh=()=>Cn&&Tl()&&(en()!=="anchor-top"||iu()),Ml=()=>{let i=Io()||"Jump to latest",m=Gh();Bt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ro>0?(Bo.textContent=String(ro),Bo.style.display="",Bt.setAttribute("aria-label",`${i} (${ro} new)`)):(Bo.textContent="",Bo.style.display="none",Bt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},ku=()=>{ro!==0&&(ro=0,Ml())},Tl=()=>Yn()?!an.isFollowing():!ko(ie,Cs),sn=()=>{if(!is()||ke){Bt.parentNode&&Bt.remove(),Bt.style.display="none";return}Bt.parentNode!==ue&&ue.appendChild(Bt),ur();let m=Dn(ie)>0&&Tl();m?Ml():ku(),Bt.style.display=m?"":"none"},ia=()=>{an.pause()&&(Eu(),sn())},ao=()=>{an.resume(),ku(),sn()},so=(i=!1)=>{Yn()&&an.isFollowing()&&(!i&&!Cn||(oo!==null&&(cancelAnimationFrame(oo),oo=null),bs=!0,oo=requestAnimationFrame(()=>{oo=null,bs=!1,an.isFollowing()&&Kh(Tu(),i?220:140)})))},Lu=(i,m,x,v=()=>!0)=>{let L=i.scrollTop,H=m(),Q=H-L;if(sa(),Math.abs(Q)<1){gn=!0,i.scrollTop=H,mn=i.scrollTop,gn=!1;return}let V=performance.now();gn=!0;let K=le=>1-Math.pow(1-le,3),oe=le=>{if(!v()){sa();return}let re=m();re!==H&&(H=re,Q=H-L);let ye=le-V,Ge=Math.min(ye/x,1),yt=K(Ge),st=L+Q*yt;i.scrollTop=st,mn=i.scrollTop,Ge<1?yr=requestAnimationFrame(oe):(i.scrollTop=H,mn=i.scrollTop,yr=null,gn=!1)};yr=requestAnimationFrame(oe)},Kh=(i,m=500)=>{let x=Dn(i)-i.scrollTop;if(Math.abs(x)<1){mn=i.scrollTop;return}if(Math.abs(x)>=zh){sa(),gn=!0,i.scrollTop=Dn(i),mn=i.scrollTop,gn=!1;return}Lu(i,()=>Dn(i),m,()=>an.isFollowing())},Pu=()=>{let i=Tu();gn=!0,i.scrollTop=Dn(i),mn=i.scrollTop,gn=!1,sn()},Ru=i=>{let m=0,x=i;for(;x&&x!==ie;)m+=x.offsetTop,x=x.offsetParent;return m},Iu=()=>{if(Wh()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(H=>H.role==="user");if(!m)return!1;let x=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ie.querySelector(`[data-message-id="${x}"]`);if(!v)return!1;let L=Math.min(Math.max(0,Ru(v)-au()),Dn(ie));return gn=!0,ie.scrollTop=L,mn=ie.scrollTop,gn=!1,en()==="follow"&&!ko(ie,Cs)&&an.pause(),sn(),!0},Bu=i=>{Zn.style.height=`${Math.max(0,Math.round(i))}px`,wn&&(wn.spacerHeight=Math.max(0,i))},la=()=>{_o!==null&&(cancelAnimationFrame(_o),_o=null),sa(),wn=null,Zn.style.height="0px"},Xh=i=>{_o!==null&&cancelAnimationFrame(_o),_o=requestAnimationFrame(()=>{_o=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ie.querySelector(`[data-message-id="${m}"]`);if(!x)return;let v=Ru(x),L=wn?.spacerHeight??0,H=ie.scrollHeight-L,{targetScrollTop:Q,spacerHeight:V}=sg({anchorOffsetTop:v,topOffset:au(),viewportHeight:ie.clientHeight,contentHeight:H});wn={initialSpacerHeight:V,contentHeightAtAnchor:H,spacerHeight:V},Bu(V),Lu(ie,()=>Q,220)})},Jh=()=>{if(Yn()){if(!an.isFollowing()||ko(ie,1))return;so(!Cn);return}if(wn&&wn.initialSpacerHeight>0){let i=ie.scrollHeight-wn.spacerHeight,m=ig({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});m!==wn.spacerHeight&&Bu(m)}sn()},Qh=i=>{let m=en();m==="follow"?(ao(),so(!0)):m==="anchor-top"&&(aa=!1,vl=!0,Xh(i))},Yh=()=>{if(en()==="anchor-top"){if(vl){aa=!1;return}aa=!0,la(),ao(),so(!0)}},Zh=i=>{let m=new Map;i.forEach(x=>{let v=wl.get(x.id);m.set(x.id,{streaming:x.streaming,role:x.role}),!v&&x.role==="assistant"&&(l.emit("assistant:message",x),!vs&&(en()!=="anchor-top"||iu())&&Tl()&&(ro+=1,Ml(),sn(),du(ro===1?"1 new message below.":`${ro} new messages below.`))),x.role==="assistant"&&v?.streaming&&x.streaming===!1&&l.emit("assistant:complete",x),x.variant==="approval"&&x.approval&&(v?x.approval.status!=="pending"&&l.emit("approval:resolved",{approval:x.approval,decision:x.approval.status}):l.emit("approval:requested",{approval:x.approval,message:x}))}),wl.clear(),m.forEach((x,v)=>{wl.set(v,x)})},ey=(i,m,x)=>{let v=document.createElement("div"),H=(()=>{let D=r.find(Ne=>Ne.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(D,Ne)=>Ne==null?!1:typeof Ne=="string"?(D.textContent=Ne,!0):(D.appendChild(Ne),!0),V=new Set,K=new Set,oe=r.some(D=>D.renderAskUserQuestion),le=[],re=[],ye=o.enableComponentStreaming!==!1,Ge=o.approval!==!1,yt=[];if(m.forEach(D=>{V.add(D.id);let Ne=oe&&jn(D),Ce=Ge&&D.variant==="approval"&&!!D.approval,Ue=!Ne&&D.role==="assistant"&&!D.variant&&ye&&rs(D);!Ce&&no.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(D.id)),!Ue&&Oo.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Oo.delete(D.id));let Mt=jn(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=eg(D,yl)+Mt,wt=Ne||Ce||Ue?null:ng(No,D.id,ut);if(wt){v.appendChild(wt.cloneNode(!0)),jn(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Pr(D,o,Le.composerOverlay));return}let xt=null,qt=r.find(ce=>!!(D.variant==="reasoning"&&ce.renderReasoning||D.variant==="tool"&&ce.renderToolCall||!D.variant&&ce.renderMessage)),Vo=o.layout?.messages;if(jn(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){hr.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Pa(D)&&o.features?.suggestReplies?.enabled!==!1)return;if(jn(D)&&o.features?.askUserQuestion?.enabled!==!1){let ce=r.find(At=>typeof At.renderAskUserQuestion=="function");if(ce&>.current){let At=hr.get(D.id),Gt=At!==ut,Ft=null;if(Gt){let{payload:et,complete:Pt}=Gn(D),Be=D.id,tt=()=>gt.current?.getMessages().find(ln=>ln.id===Be);Ft=ce.renderAskUserQuestion({message:D,payload:et,complete:Pt,resolve:ln=>{let zo=tt();zo&>.current?.resolveAskUserQuestion(zo,ln)},dismiss:()=>{let ln=tt();ln?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(ln),gt.current?.resolveAskUserQuestion(ln,"(dismissed)"))},config:o})}let rt=At!=null;if(Gt&&Ft===null&&!rt){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Pr(D,o,Le.composerOverlay));return}let $e=document.createElement("div");$e.className="persona-flex",$e.id=`wrapper-${D.id}`,$e.setAttribute("data-wrapper-id",D.id),$e.setAttribute("data-ask-plugin-stub","true"),$e.setAttribute("data-preserve-runtime","true"),v.appendChild($e),le.push({messageId:D.id,fingerprint:ut,bubble:Ft});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(K.add(D.toolCall.id),Pr(D,o,Le.composerOverlay));return}}else if(Ce){let ce=r.find(rt=>typeof rt.renderApproval=="function")??a,Gt=no.get(D.id)!==ut,Ft=null;if(Gt&&ce?.renderApproval){let rt=D.id,$e=(et,Pt)=>{let Be=gt.current?.getMessages().find(tt=>tt.id===rt);Be?.approval&&(Be.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(Be.id,et):gt.current?.resolveApproval(Be.approval,et,Pt))};Ft=ce.renderApproval({message:D,defaultRenderer:()=>Xi(D,o),config:o,approve:et=>$e("approved",et),deny:et=>$e("denied",et)})}if(Gt&&Ft===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),no.delete(D.id),xt=Xi(D,o);else{let rt=document.createElement("div");rt.className="persona-flex",rt.id=`wrapper-${D.id}`,rt.setAttribute("data-wrapper-id",D.id),rt.setAttribute("data-approval-plugin-stub","true"),rt.setAttribute("data-preserve-runtime","true"),v.appendChild(rt),yt.push({messageId:D.id,fingerprint:ut,bubble:Ft});return}}else if(qt)if(D.variant==="reasoning"&&D.reasoning&&qt.renderReasoning){if(!se)return;xt=qt.renderReasoning({message:D,defaultRenderer:()=>Rp(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&qt.renderToolCall){if(!be)return;xt=qt.renderToolCall({message:D,defaultRenderer:()=>Bp(D,o),config:o})}else qt.renderMessage&&(xt=qt.renderMessage({message:D,defaultRenderer:()=>{let ce=zr(D,x,Vo,o.messageActions,_e,{loadingIndicatorRenderer:H,widgetConfig:o});return D.role!=="user"&&_p(ce,D,o,z),ce},config:o}));if(!xt&&Ue){let ce=el(D);if(ce){let At=Oo.get(D.id),Gt=At!==ut,Ft=o.wrapComponentDirectiveInBubble!==!1&&kn.getOptions(ce.component)?.bubbleChrome!==!1,rt=null;if(Gt){let $e=Zi(ce,{config:o,message:D,transform:x});if($e&&ce.component==="PersonaArtifactInline"){let et=$e.hasAttribute("data-artifact-inline")?$e:$e.querySelector("[data-artifact-inline]"),Pt=et?.getAttribute("data-artifact-inline")??"",Be=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Pt):Pt,tt=Pt?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${Be}"]`)??null:null;et&&tt&&tt!==et&&Km(tt)&&(et===$e?$e=tt:et.replaceWith(tt))}if($e)if(Ft){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${D.id}`,et.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let Pt=document.createElement("div");Pt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Pt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),et.appendChild(Pt)}et.appendChild($e),rt=et}else{let et=document.createElement("div");if(et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",et.id=`bubble-${D.id}`,et.setAttribute("data-message-id",D.id),et.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let Pt=document.createElement("div");Pt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Pt.innerHTML=x({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),et.appendChild(Pt)}et.appendChild($e),rt=et}}if(rt||At!=null){let $e=document.createElement("div");$e.className="persona-flex",$e.id=`wrapper-${D.id}`,$e.setAttribute("data-wrapper-id",D.id),$e.setAttribute("data-component-directive-stub","true"),$e.setAttribute("data-preserve-runtime","true"),Ft||$e.classList.add("persona-w-full"),v.appendChild($e),re.push({messageId:D.id,fingerprint:ut,bubble:rt});return}}}if(!xt)if(D.variant==="reasoning"&&D.reasoning){if(!se)return;xt=Rp(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!be)return;xt=Bp(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;xt=Xi(D,o)}else{let ce=o.layout?.messages;ce?.renderUserMessage&&D.role==="user"?xt=ce.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):ce?.renderAssistantMessage&&D.role==="assistant"?xt=ce.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):xt=zr(D,x,ce,o.messageActions,_e,{loadingIndicatorRenderer:H,widgetConfig:o}),D.role!=="user"&&xt&&_p(xt,D,o,z)}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${D.id}`,ft.setAttribute("data-wrapper-id",D.id),D.role==="user"&&ft.classList.add("persona-justify-end"),xt?.getAttribute("data-persona-component-directive")==="true"&&ft.classList.add("persona-w-full"),ft.appendChild(xt),og(No,D.id,ut,ft),v.appendChild(ft)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Ce=Ne.getAttribute("data-persona-ask-sheet-for");Ce&&!K.has(Ce)&&go(Le.composerOverlay,Ce)}),o.features?.toolCallDisplay?.grouped){let D=[],Ne=[];m.forEach(Ce=>{if(Ce.variant==="tool"&&Ce.toolCall&&be){Ne.push(Ce);return}Ce.variant==="reasoning"&&!se||(Ne.length>1&&D.push(Ne),Ne=[])}),Ne.length>1&&D.push(Ne),D.forEach((Ce,Ue)=>{let Mt=Ce.map(At=>Array.from(v.children).find(Gt=>Gt instanceof HTMLElement&&Gt.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);if(Mt.length<2)return;let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-tool-group-${Ue}-${Ce[0].id}`,ut.setAttribute("data-wrapper-id",`tool-group-${Ue}-${Ce[0].id}`);let wt=document.createElement("div");wt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",wt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Ce.length} tools`,Vo=o.toolCall?.renderGroupedSummary?.({messages:Ce,toolCalls:Ce.map(At=>At.toolCall).filter(At=>!!At),defaultSummary:qt,config:o});Q(xt,Vo)||(xt.textContent=qt);let ft=document.createElement("div");ft.className="persona-tool-group-stack persona-flex persona-flex-col";let ce=o.features?.toolCallDisplay?.groupedMode==="summary";wt.appendChild(xt),ce||wt.appendChild(ft),ut.appendChild(wt),Mt[0].before(ut),Mt.forEach((At,Gt)=>{if(ce){At.remove();return}let Ft=document.createElement("div");Ft.className="persona-tool-group-item persona-relative",Ft.setAttribute("data-persona-tool-group-item","true"),Gt<Mt.length-1&&Ft.setAttribute("data-persona-tool-group-connector","true"),Ft.appendChild(At),ft.appendChild(Ft)})})}rg(No,V);let st=m.some(D=>D.role==="assistant"&&D.streaming),jt=m[m.length-1],Dt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(Cn&&m.some(D=>D.role==="user")&&!st&&!Dt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:ir},Ne=r.find(Ue=>Ue.renderLoadingIndicator),Ce=null;if(Ne?.renderLoadingIndicator&&(Ce=Ne.renderLoadingIndicator(D)),Ce===null&&o.loadingIndicator?.render&&(Ce=o.loadingIndicator.render(D)),Ce===null&&(Ce=ir()),Ce){let Ue=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;Ue.className=Mt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ue.setAttribute("data-typing-indicator","true"),Ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ue.appendChild(Ce);let ut=document.createElement("div");ut.className="persona-flex",ut.id="wrapper-typing-indicator",ut.setAttribute("data-wrapper-id","typing-indicator"),ut.appendChild(Ue),v.appendChild(ut)}}if(!Cn&&m.length>0){let D=m[m.length-1],Ne={config:o,lastMessage:D,messageCount:m.length},Ce=r.find(Mt=>Mt.renderIdleIndicator),Ue=null;if(Ce?.renderIdleIndicator&&(Ue=Ce.renderIdleIndicator(Ne)),Ue===null&&o.loadingIndicator?.renderIdle&&(Ue=o.loadingIndicator.renderIdle(Ne)),Ue){let Mt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Mt.className=ut?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(Ue);let wt=document.createElement("div");wt.className="persona-flex",wt.id="wrapper-idle-indicator",wt.setAttribute("data-wrapper-id","idle-indicator"),wt.appendChild(Mt),v.appendChild(wt)}}if(Ri(i,v),le.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ce}of le){let Ue=i.querySelector(`#wrapper-${D}`);Ue&&Ce!==null&&(Ue.replaceChildren(Ce),Ue.setAttribute("data-bubble-fp",Ne),hr.set(D,Ne))}if(hr.size>0)for(let D of hr.keys())V.has(D)||hr.delete(D);if(re.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ce}of re){let Ue=i.querySelector(`#wrapper-${D}`);Ue&&Ce!==null&&(Ue.replaceChildren(Ce),Ue.setAttribute("data-bubble-fp",Ne),Oo.set(D,Ne))}if(Oo.size>0)for(let D of Oo.keys())V.has(D)||Oo.delete(D);if(yt.length>0)for(let{messageId:D,fingerprint:Ne,bubble:Ce}of yt){let Ue=i.querySelector(`#wrapper-${D}`);Ue&&Ce!==null&&(Ue.replaceChildren(Ce),Ue.setAttribute("data-bubble-fp",Ne),no.set(D,Ne))}if(no.size>0)for(let D of no.keys())V.has(D)||no.delete(D)},da=(i,m,x)=>{ey(i,m,x),yu()},ca=null,ty=()=>{if(ca)return;let i=x=>{let v=x.composedPath();v.includes(Me)||lt&&v.includes(lt)||ht(!1,"user")};ca=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Hu=()=>{if(!ca)return;(e.ownerDocument??document).removeEventListener("pointerdown",ca,!0),ca=null};je.push(()=>Hu());let pa=null,ny=()=>{if(pa)return;let i=x=>{x.key==="Escape"&&(x.isComposing||ht(!1,"user"))};pa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Wu=()=>{if(!pa)return;(e.ownerDocument??document).removeEventListener("keydown",pa,!0),pa=null};je.push(()=>Wu());let ua=!1,Du=new Set,oy=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},xr=()=>{if(!$())return;let i=Le.peekBanner,m=Le.peekTextNode;if(!i||!m)return;if(U){i.classList.remove("persona-pill-peek--visible");return}let x=z?.getMessages()??[],v;for(let Dt=x.length-1;Dt>=0;Dt--){let D=x[Dt];if(D.role==="assistant"&&D.content){v=D;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let L=v.content,H=!!v.streaming,Q=oy(),V=Wi(Q),K=V.type!=="none"?Ur(V.type,Q?.plugins):null,oe=K?.isAnimating?.(v)===!0,le=K!==null&&(H||oe);le&&K&&!Du.has(K.name)&&(Ni(K,e),Du.add(K.name));let re=le&&K?.containerClass?K.containerClass:null,ye=m.dataset.personaPeekStreamClass??null;ye&&ye!==re&&(m.classList.remove(ye),delete m.dataset.personaPeekStreamClass),re&&ye!==re&&(m.classList.add(re),m.dataset.personaPeekStreamClass=re),le?(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 Ge=le?Di(L,V.buffer,K,v,H):L;if(le&&V.placeholder==="skeleton"&&H&&(!Ge||!Ge.trim())){let Dt=document.createElement("div"),D=Ga();D.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(D),Ri(m,Dt)}else{let Dt=Math.max(0,Ge.length-100),D=Ge.length>100?Ge.slice(-100):Ge,Ne=Bn(D);if(!le||!K){let Ce=Ge.length>100?`\u2026${D}`:D;m.textContent!==Ce&&(m.textContent=Ce)}else{let Ce=Ne;(K.wrap==="char"||K.wrap==="word")&&(Ce=ja(Ne,K.wrap,`peek-${v.id}`,{skipTags:K.skipTags,startIndex:Dt}));let Ue=document.createElement("div");if(Ue.innerHTML=Ce,K.useCaret&&D.length>0){let Mt=Fi(),ut=Ue.querySelectorAll(".persona-stream-char, .persona-stream-word"),wt=ut[ut.length-1];wt?.parentNode?wt.parentNode.insertBefore(Mt,wt.nextSibling):Ue.appendChild(Mt)}Ri(m,Ue),K.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let jt=Cn||ua;i.classList.toggle("persona-pill-peek--visible",jt)};if($()){let i=Le.peekBanner;if(i){let v=L=>{L.preventDefault(),L.stopPropagation(),ht(!0,"user")};i.addEventListener("pointerdown",v),je.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ua||(ua=!0,xr())},x=()=>{ua&&(ua=!1,xr())};me.addEventListener("pointerenter",m),me.addEventListener("pointerleave",x),je.push(()=>{me.removeEventListener("pointerenter",m),me.removeEventListener("pointerleave",x)}),lt&&(lt.addEventListener("pointerenter",m),lt.addEventListener("pointerleave",x),je.push(()=>{lt.removeEventListener("pointerenter",m),lt.removeEventListener("pointerleave",x)}))}let ry=i=>{let m=o.launcher?.composerBar??{},x=m.expandedSize??"anchored",v=m.bottomOffset??"16px",L=m.collapsedMaxWidth,H=m.expandedMaxWidth??"880px",Q=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",K=m.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",re=Me.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",lt){let ye=lt.style;ye.bottom=v,ye.width=L??""}if(i&&x!=="fullscreen"){if(x==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=V,re.maxWidth=oe,re.maxHeight=K,re.height=K;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${le})`,re.top=Q,re.width=H,re.maxWidth=oe}},fa=()=>{if(!N())return;if($()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=U?"expanded":"collapsed";Me.dataset.state=le,Me.dataset.expandedSize=oe,lt&&(lt.dataset.state=le,lt.dataset.expandedSize=oe),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ry(U),ue.style.display=U?"flex":"none",hs(),U?(ty(),ny()):(Hu(),Wu()),xr();return}let i=It(o),m=e.ownerDocument.defaultView??window,x=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,L=m.innerWidth<=x,H=v&&L&&A,Q=on(o).reveal;U?(Me.style.removeProperty("display"),Me.style.display=i?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),_t?_t.element.style.display="none":$t&&($t.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!H?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=i?"none":"":$t&&($t.style.display=i?"none":""))},ht=(i,m="user")=>{if(!N()||U===i)return;let x=U;U=i,fa();let v=(()=>{let H=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,oe=Q.innerWidth<=K,le=It(o)&&V&&oe,re=$()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return H||V&&oe&&A||le||re})();if(U&&v){if(!Pn){let H=e.getRootNode(),Q=H instanceof ShadowRoot?H.host:e.closest(".persona-host");Q&&(Pn=vp(Q,o.launcher?.zIndex??zt))}Rn||(Rn=Cp(e.ownerDocument))}else U||(Pn?.(),Pn=null,Rn?.(),Rn=null);U&&(ha(),Iu()||(en()==="follow"?so(!0):Pu()));let L={open:U,source:m,timestamp:Date.now()};U&&!x?l.emit("widget:opened",L):!U&&x&&l.emit("widget:closed",L),l.emit("widget:state",{open:U,launcherEnabled:A,voiceActive:Je.active,streaming:z.isStreaming()})},El=i=>{dt(i?"stop":"send"),G&&(G.disabled=i),xs.buttons.forEach(m=>{m.disabled=i}),j.dataset.personaComposerStreaming=i?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},kl=()=>{Je.active||q&&q.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>kl(),200)});let Fu=()=>{J.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",C.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",q.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let x=o.copy?.showWelcomeCard!==!1;i.style.display=x?"":"none",x?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(te.textContent=o.copy?.sendButtonLabel??"Send"),q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',q.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=d.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(m=>({...m,sessionId:i}))}});let Uo=null,ay=()=>{Uo==null&&(Uo=setInterval(()=>{let i=he.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let m=Date.now();i.forEach(x=>{let v=Number(x.getAttribute("data-tool-elapsed"));v&&(x.textContent=js(m-v))})},100))},Ll=(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((Q,V)=>Ll(Q,m[V]));let x=i,v=m,L=Object.keys(x),H=Object.keys(v);return L.length===H.length&&L.every(Q=>Object.prototype.hasOwnProperty.call(v,Q)&&Ll(x[Q],v[Q]))},Nu=i=>{let{content:m,rawContent:x,llmContent:v,...L}=i;return L},Pl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!rs(i),sy=(i,m,x)=>{if(i.length!==m.length)return!1;let v=i[x.index],L=m[x.index];return!v||!L||v.id!==x.id||L.id!==x.id?!1:(!Object.is(v.content,L.content)||!Object.is(v.rawContent,L.rawContent)||!Object.is(v.llmContent,L.llmContent))&&Pl(v)&&Pl(L)&&Ll(Nu(v),Nu(L))},Ou=null,br=null,qo=null,Un=null,As=i=>{Ou=i;let m,x;br=null;for(let L=i.length-1;L>=0;L-=1){let H=i[L];if(!m&&H.role==="user"&&(m=H),!x&&H.role==="assistant"&&(x=H),!br&&Pl(H)&&(br={index:L,id:H.id}),m&&x&&br)break}da(he,i,Fe),up(he,bn.artifacts,{suppressTransition:Cn}),ay(),hl(i),so(!Cn),Zh(i),i.length===0&&(la(),aa=!0,vl=!1),!xl||vs?(xl=!0,bl=m?.id??null,Cl=x?.id??null):m&&m.id!==bl?(bl=m.id,Qh(m.id)):x&&x.id!==Cl&&Yh(),x&&(Cl=x.id);let v=Je.lastUserMessageId;m&&m.id!==v&&(Je.lastUserMessageId=m.id,l.emit("user:message",m)),Je.lastUserMessageWasVoice=!!m?.viaVoice,Sl(i),xr()},Rl=()=>{Un!==null&&(cancelAnimationFrame(Un),Un=null);let i=qo;qo=null,i&&As(i)},_u=()=>{Un!==null&&cancelAnimationFrame(Un),Un=null,qo=null},iy=i=>{let m=qo??Ou;if(Cn&&m&&br&&sy(m,i,br)){qo=i,Un===null&&(Un=requestAnimationFrame(()=>{Un=null;let x=qo;qo=null,x&&As(x)}));return}if(i.length===0){_u(),As(i);return}Rl(),As(i)};z=new Hr(o,{onMessagesChanged(i){iy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Lt(I,(v=>v==="idle"?m.idleText??Wt.idle:v==="connecting"?m.connectingText??Wt.connecting:v==="connected"?m.connectedText??Wt.connected:v==="error"?m.errorText??Wt.error:v==="paused"?m.pausedText??Wt.paused:v==="resuming"?m.resumingText??Wt.resuming:Wt[v])(i),m,i)},onStreamingChanged(i){i||(z?.getMessages().length===0?_u():Rl()),Cn=i,El(i),z&&da(he,z.getMessages(),Fe),i||so(!0),sn(),du(i?"Responding\u2026":"Response complete."),xr()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":qn(),Cr();break;case"processing":qn(),xy();break;case"speaking":qn(),by();break;default:i==="idle"&&z.isBargeInActive()?(qn(),Cr(),G?.setAttribute("aria-label","End voice session")):(Je.active=!1,qn(),_n("system"),An());break}},onArtifactsState(i){bn=i,i.artifacts.length===0&&(fr=!1),up(he,i.artifacts,{suppressTransition:Cn}),On(),Sl()},onReconnect(i){let{executionId:m,lastEventId:x}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:m,after:x}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:m,after:x,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:m,after:x})}}),gt.current=z,je.push(()=>z.cancel());let Il=null;if(z.onReadAloudChange((i,m)=>{gu=i,hu=m,yu();let x=i??Il;i&&(Il=i);let v=x?z.getMessages().find(L=>L.id===x)??null:null;l.emit("message:read-aloud",{messageId:x,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(Il=null)}),xl=!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)}),(Oe||o.onSSEEvent)&&z.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),Xe?.processEvent(i,m),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let Uu=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(d=Vp(i.metadata),M.syncFromMetadata()),i.messages?.length){vs=!0;try{z.hydrateMessages(i.messages)}finally{vs=!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(()=>Uu()):Uu();let qu=()=>{!$()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},ly=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[x,v]=await Promise.allSettled([i.finalize(),m.finalize()]),L=[];return x.status==="fulfilled"?L.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),v.status==="fulfilled"?L.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),bC(L)}}:i:m,dy=()=>{let m=q.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},ma=!1,cy=async i=>{let m=q.value.trim(),x=Tt?.hasAttachments()??!1,v=m?await(rn?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){q.value="",q.style.height="auto",ga(),rn?.clear();return}let L=rn?.collectForSubmit()??null,H=v?.kind==="server"?v.mentions:null,Q=ly(L,H),V=v?.kind==="prompt"?v.sendText:m,K=!!L&&L.refs.length>0;if(!V&&!x&&!K&&!H)return;qu();let oe;x&&(oe=[],oe.push(...Tt.getContentParts()),V&&oe.push(bo(V)));let le=v?.kind==="prompt"?void 0:dy();q.value="",q.style.height="auto",ga(),z.sendMessage(V,{contentParts:oe,mentions:Q??void 0,contentSegments:le,viaVoice:i?.viaVoice}),x&&Tt.clearAttachments(),L&&rn?.clear()},Bl=async i=>{if(!ma){ma=!0;try{await cy(i)}finally{ma=!1}}},Vu=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),Xe?.reset(),qe?.update();return}ma||Bl()},py=()=>o.features?.composerHistory!==!1,Hl={...gp},Wl=!1,ga=()=>{Hl={...gp}},uy=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),fy=i=>{if(!q)return;Wl=!0,q.value=i,q.dispatchEvent(new Event("input",{bubbles:!0})),Wl=!1;let m=q.value.length;q.setSelectionRange(m,m)},my=i=>{Wl||(i.isComposing||rn?.handleInput(i.inputType??void 0),ga())},gy=i=>{if(q&&!(!i.isComposing&&rn?.handleKeydown(i))){if(py()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=q.selectionStart===0&&q.selectionEnd===0,x=Zm({direction:i.key==="ArrowUp"?"up":"down",history:uy(),currentValue:q.value,atStart:m,state:Hl});if(Hl=x.state,x.handled){i.preventDefault(),x.value!==void 0&&fy(x.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(ma){i.preventDefault();return}ga(),i.preventDefault(),te.click()}}},zu=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(ue)&&(z.cancel(),Xe?.reset(),qe?.update(),ga(),i.preventDefault(),i.stopImmediatePropagation())},hy=async i=>{if(o.attachments?.enabled!==!0||!Tt)return;let m=gC(i.clipboardData);m.length!==0&&(i.preventDefault(),await Tt.handleFiles(m))},hn=null,In=!1,vr=null,Ct=null,$u=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ss=(i="user")=>{if(In||z.isStreaming())return;let m=$u();if(!m)return;hn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;hn.continuous=!0,hn.interimResults=!0,hn.lang="en-US";let L=q.value;hn.onresult=H=>{let Q="",V="";for(let oe=0;oe<H.results.length;oe++){let le=H.results[oe],re=le[0].transcript;le.isFinal?Q+=re+" ":V=re}let K=L+Q+V;q.value=K,vr&&clearTimeout(vr),(Q||V)&&(vr=window.setTimeout(()=>{q.value.trim()&&hn&&In&&(io(),Bl({viaVoice:!0}))},v))},hn.onerror=H=>{H.error!=="no-speech"&&io()},hn.onend=()=>{if(In){let H=q.value.trim();H&&H!==L.trim()&&Bl({viaVoice:!0}),io()}};try{if(hn.start(),In=!0,Je.active=!0,i!=="system"&&(Je.manuallyDeactivated=!1),_n(i),An(),G){let H=o.voiceRecognition??{};Ct={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:H.iconName??"mic",iconSize:parseFloat(H.iconSize??o.sendButton?.size??"40")||24};let Q=H.recordingBackgroundColor,V=H.recordingIconColor,K=H.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let oe=G.querySelector("svg");oe&&oe.setAttribute("stroke",V)}K&&(G.style.borderColor=K),G.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(i="user")=>{if(In){if(In=!1,vr&&(clearTimeout(vr),vr=null),hn){try{hn.stop()}catch{}hn=null}if(Je.active=!1,_n(i),An(),G){if(G.classList.remove("persona-voice-recording"),Ct){G.style.backgroundColor=Ct.backgroundColor,G.style.color=Ct.color,G.style.borderColor=Ct.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}G.setAttribute("aria-label","Start voice recognition")}}},yy=(i,m)=>{let x=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",L=i?.provider?.type==="custom";if(!(x||v||L))return null;let Q=y("div","persona-send-button-wrapper"),V=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button",V.setAttribute("aria-label","Start voice recognition");let K=i?.iconName??"mic",oe=m?.size??"40px",le=i?.iconSize??oe,re=parseFloat(le)||24,ye=i?.backgroundColor??m?.backgroundColor,Ge=i?.iconColor??m?.textColor;V.style.width=le,V.style.height=le,V.style.minWidth=le,V.style.minHeight=le,V.style.fontSize="18px",V.style.lineHeight="1",Ge?V.style.color=Ge:V.style.color="var(--persona-text, #111827)";let st=ne(K,re,Ge||"currentColor",1.5);st?V.appendChild(st):V.textContent="\u{1F3A4}",ye?V.style.backgroundColor=ye: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),Q.appendChild(V);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let D=y("div","persona-send-button-tooltip");D.textContent=jt,Q.appendChild(D)}return{micButton:V,micButtonWrapper:Q}},Dl=()=>{if(!G||Ct)return;let i=o.voiceRecognition??{};Ct={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}},Fl=(i,m)=>{if(!G)return;let x=G.querySelector("svg");x&&x.remove();let v=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),L=ne(i,v,m,1.5);L&&G.appendChild(L)},Ms=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Cr=()=>{if(!G)return;Dl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,x=i.recordingIconColor,v=i.recordingBorderColor;if(Ms(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=x??"var(--persona-voice-recording-indicator, #ffffff)",x){let L=G.querySelector("svg");L&&L.setAttribute("stroke",x)}v&&(G.style.borderColor=v),G.setAttribute("aria-label","Stop voice recognition")},xy=()=>{if(!G)return;Dl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),x=i.processingIconName??"loader",v=i.processingIconColor??Ct?.color??"",L=i.processingBackgroundColor??Ct?.backgroundColor??"",H=i.processingBorderColor??Ct?.borderColor??"";Ms(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=H;let Q=v||"currentColor";G.style.color=Q,Fl(x,Q),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},by=()=>{if(!G)return;Dl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),x=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??x,L=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??Ct?.color??"":Ct?.color??""),H=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),Q=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Ms(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=H,G.style.borderColor=Q;let V=L||"currentColor";G.style.color=V,Fl(v,V);let K=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",K),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},qn=()=>{G&&(Ms(),Ct&&(G.style.backgroundColor=Ct.backgroundColor??"",G.style.color=Ct.color??"",G.style.borderColor=Ct.borderColor??"",Fl(Ct.iconName,Ct.color||"currentColor"),Ct=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ts=()=>{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(()=>{Je.active=!1,Je.manuallyDeactivated=!0,An(),_n("user"),qn()});return}z.toggleVoice().then(()=>{Je.active=z.isVoiceActive(),Je.manuallyDeactivated=!z.isVoiceActive(),An(),_n("user"),z.isVoiceActive()?Cr():qn()});return}if(In){let i=q.value.trim();Je.manuallyDeactivated=!0,An(),io("user"),i&&(q.value="",q.style.height="auto",z.sendMessage(i))}else Je.manuallyDeactivated=!1,An(),Ss("user")};pu=Ts,G&&(G.addEventListener("click",Ts),je.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),qn()):io("system"),G&&G.removeEventListener("click",Ts)}));let vy=l.on("assistant:complete",()=>{Su&&(Je.active||Je.manuallyDeactivated||Su==="assistant"&&!Je.lastUserMessageWasVoice||setTimeout(()=>{!Je.active&&!Je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Je.active=z.isVoiceActive(),_n("auto"),z.isVoiceActive()&&Cr()}):Ss("auto"))},600))});je.push(vy);let Cy=l.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});je.push(Cy);let ju=()=>{ht(!U,"user")},_t=null,$t=null;if(A&&!$()){let{instance:i,element:m}=Tp({config:o,plugins:r,onToggle:ju});_t=i,i||($t=m)}_t?e.appendChild(_t.element):$t&&e.appendChild($t),fa(),hl(),Fu(),El(z.isStreaming()),Iu()||(en()==="follow"?so(!0):Pu()),$h(),T&&(!A||$()?setTimeout(()=>kl(),0):U&&setTimeout(()=>kl(),200));let ha=()=>{if($()){ur(),fa();return}let i=It(o),m=o.launcher?.sidebarMode??!1,x=i||m||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,Q=v.innerWidth<=H,V=L&&Q&&A;try{if(V){ta(),na=gs();return}let K=!1;F&&(F=!1,ta(),K=!0);let oe=gs();if(!K&&oe!==na&&(ta(),K=!0),na=oe,K&&ml(),!A&&!i){me.style.height="",me.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??pn;me.style.width=re,me.style.maxWidth=re}if(ms(),!x){let le=v.innerHeight,re=64,ye=o.launcher?.heightOffset??0,Ge=Math.max(200,le-re),yt=Math.min(640,Ge),st=Math.max(200,yt-ye);me.style.height=`${st}px`}}finally{if(ur(),fa(),U&&A){let oe=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,ye=It(o)&&re&&oe,Ge=le||re&&oe&&A||ye;if(Ge&&!Rn){let yt=e.getRootNode(),st=yt instanceof ShadowRoot?yt.host:e.closest(".persona-host");st&&!Pn&&(Pn=vp(st,o.launcher?.zIndex??zt)),Rn=Cp(e.ownerDocument)}else Ge||(Pn?.(),Pn=null,Rn?.(),Rn=null)}}};ha();let Gu=e.ownerDocument.defaultView??window;if(Gu.addEventListener("resize",ha),je.push(()=>Gu.removeEventListener("resize",ha)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ur()});i.observe(j),je.push(()=>i.disconnect())}mn=ie.scrollTop;let Ku=Dn(ie),wy=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Nl=()=>ag(wy(),ie),Xu=()=>{let i=ie.scrollTop,m=Dn(ie),x=m<Ku;if(Ku=m,!Yn()){mn=i,sn();return}let{action:v,nextLastScrollTop:L}=Bi({following:an.isFollowing(),currentScrollTop:i,lastScrollTop:mn,nearBottom:ko(ie,Cs),userScrollThreshold:Vh,isAutoScrolling:gn||bs||x,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(mn=L,v==="resume"){Nl()||ao();return}v==="pause"&&ia()};if(ie.addEventListener("scroll",Xu,{passive:!0}),je.push(()=>ie.removeEventListener("scroll",Xu)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Jh()});i.observe(he),i.observe(ie),je.push(()=>i.disconnect())}let Ju=()=>{Yn()&&an.isFollowing()&&Nl()&&ia()},Qu=ie.ownerDocument;Qu.addEventListener("selectionchange",Ju),je.push(()=>{Qu.removeEventListener("selectionchange",Ju)});let Ay=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Yu=i=>{su()&&Yn()&&an.isFollowing()&&Ay.has(i.key)&&ia()},Zu=i=>{if(!su()||!Yn()||!an.isFollowing())return;let m=i.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&ia()};ie.addEventListener("keydown",Yu),ie.addEventListener("focusin",Zu),je.push(()=>{ie.removeEventListener("keydown",Yu),ie.removeEventListener("focusin",Zu)});let ef=i=>{if(!Yn())return;let m=Hi({following:an.isFollowing(),deltaY:i.deltaY,nearBottom:ko(ie,Cs),resumeWhenNearBottom:!0});m==="pause"?ia():m==="resume"&&!Nl()&&ao()};ie.addEventListener("wheel",ef,{passive:!0}),je.push(()=>ie.removeEventListener("wheel",ef)),Bt.addEventListener("click",()=>{la(),ie.scrollTop=ie.scrollHeight,mn=ie.scrollTop,ao(),so(!0),sn()}),je.push(()=>Bt.remove()),je.push(()=>{Eu(),la()});let tf=()=>{P&&(Fo&&(P.removeEventListener("click",Fo),Fo=null),N()?(P.style.display="",Fo=()=>{ht(!1,"user")},P.addEventListener("click",Fo)):P.style.display="none")};tf(),(()=>{let{clearChatButton:i}=Le;i&&i.addEventListener("click",()=>{z.clearMessages(),No.clear(),ao(),go(Le.composerOverlay);try{localStorage.removeItem(Xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xr}`)}catch(x){console.error("[AgentWidget] Failed to clear default localStorage:",x)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(x){console.error("[AgentWidget] Failed to clear custom localStorage:",x)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),c?.clear&&Al(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Oe?.clear(),Xe?.reset(),qe?.update()})})(),Ae&&Ae.addEventListener("submit",Vu);let nf=[["keydown",gy],["input",my],["paste",hy],["focus",Nh]],of=i=>{if(i)for(let[m,x]of nf)i.addEventListener(m,x)},rf=i=>{if(i)for(let[m,x]of nf)i.removeEventListener(m,x)};of(q),rn?.onComposerSwap((i,m)=>{rf(m),q=i,of(i)});let af=e.ownerDocument??document;af.addEventListener("keydown",zu,!0);let sf="persona-attachment-drop-active",ya=0,Ol=()=>{ya=0,ue.classList.remove(sf)},wr=()=>o.attachments?.enabled===!0&&Tt!==null,lf=i=>{!ol(i.dataTransfer)||!wr()||(ya++,ya===1&&ue.classList.add(sf))},df=i=>{!ol(i.dataTransfer)||!wr()||(ya--,ya<=0&&Ol())},cf=i=>{!ol(i.dataTransfer)||!wr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},pf=i=>{if(!ol(i.dataTransfer)||!wr())return;i.preventDefault(),i.stopPropagation(),Ol();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&Tt.handleFiles(m)},lo=!0;ue.addEventListener("dragenter",lf,lo),ue.addEventListener("dragleave",df,lo),e.addEventListener("dragover",cf,lo),e.addEventListener("drop",pf,lo);let Es=e.ownerDocument,uf=i=>{wr()&&i.preventDefault()},ff=i=>{wr()&&i.preventDefault()};Es.addEventListener("dragover",uf),Es.addEventListener("drop",ff),je.push(()=>{Ae&&Ae.removeEventListener("submit",Vu),rf(q),af.removeEventListener("keydown",zu,!0),rn?.destroy()}),je.push(()=>{ue.removeEventListener("dragenter",lf,lo),ue.removeEventListener("dragleave",df,lo),e.removeEventListener("dragover",cf,lo),e.removeEventListener("drop",pf,lo),Es.removeEventListener("dragover",uf),Es.removeEventListener("drop",ff),Ol()}),je.push(()=>{z.cancel()}),_t?je.push(()=>{_t?.destroy()}):$t&&je.push(()=>{$t?.remove()});let Ht={update(i){let m=o.toolCall,x=o.messageActions,v=o.layout?.messages,L=o.colorScheme,H=o.loadingIndicator,Q=o.iterationDisplay,V=o.features?.showReasoning,K=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,le=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o={...o,...i},hs(),or(e,o),Za(e,o),es(e,o),On(),o.colorScheme!==L&&Au();let ye=ts.getForInstance(o.plugins);r.length=0,r.push(...ye),A=o.launcher?.enabled??!0,w=o.launcher?.autoExpand??!1,se=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,de=o.features?.scrollToBottom??{};let Ge=en();Y=o.features?.scrollBehavior??{},Ge!==en()&&(la(),ao()),cu(),sn();let yt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!yt){if(Oe||(xe=new Qa(we),Oe=new Ja(He,xe),Xe=Xe??new Ya,xe.open().then(()=>Oe?.restore()).catch(()=>{}),z.setSSEEventCallback((ee,ot)=>{o.onSSEEvent?.(ee,ot),Xe?.processEvent(ee,ot),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(ot)})})),!at&&_){let ee=o.features?.eventStream?.classNames,ot="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");at=y("button",ot),at.style.width="28px",at.style.height="28px",at.style.color=Qt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let St=ne("activity","18px","currentColor",1.5);St&&at.appendChild(St);let Ke=Le.clearChatButtonWrapper,ct=Le.closeButtonWrapper,Vt=Ke||ct;Vt&&Vt.parentNode===_?_.insertBefore(at,Vt):_.appendChild(at),at.addEventListener("click",()=>{ke?Zr():cl()})}}else!Z&&yt&&(Zr(),at&&(at.remove(),at=null),Oe?.clear(),xe?.destroy(),Oe=null,xe=null,Xe?.reset(),Xe=null);if(o.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),o.launcher?.enabled===!1&&$t&&($t.remove(),$t=null),o.launcher?.enabled!==!1&&!_t&&!$t){let{instance:ee,element:ot}=Tp({config:o,plugins:r,onToggle:ju});_t=ee,ee||($t=ot),e.appendChild(ot)}_t&&_t.update(o),O&&o.launcher?.title!==void 0&&(O.textContent=o.launcher.title),X&&o.launcher?.subtitle!==void 0&&(X.textContent=o.launcher.subtitle);let st=o.layout?.header;if(st?.layout!==W&&_){let ee=st?qr(o,st,{showClose:N(),onClose:()=>ht(!1,"user")}):Qn({config:o,showClose:N(),onClose:()=>ht(!1,"user")});mt.replaceHeader(ee),_=mt.header.element,B=mt.header.iconHolder,O=mt.header.headerTitle,X=mt.header.headerSubtitle,P=mt.header.closeButton,W=st?.layout}else if(st&&(B&&(B.style.display=st.showIcon===!1?"none":""),O&&(O.style.display=st.showTitle===!1?"none":""),X&&(X.style.display=st.showSubtitle===!1?"none":""),P&&(P.style.display=st.showCloseButton===!1?"none":""),Le.clearChatButtonWrapper)){let ee=st.showClearChat;if(ee!==void 0){Le.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:ot}=Le;ot&&!ot.classList.contains("persona-absolute")&&(ee?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}let Dt=o.layout?.showHeader!==!1;_&&(_.style.display=Dt?"":"none");let D=o.layout?.showFooter!==!1;j&&(j.style.display=D?"":"none"),ur(),sn(),A!==b?A?ht(w,"auto"):(U=!0,fa()):w!==R&&ht(w,"auto"),R=w,b=A,ha(),tf();let Ue=JSON.stringify(i.toolCall)!==JSON.stringify(m),Mt=JSON.stringify(o.messageActions)!==JSON.stringify(x),ut=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),wt=o.loadingIndicator?.render!==H?.render||o.loadingIndicator?.renderIdle!==H?.renderIdle||o.loadingIndicator?.showBubble!==H?.showBubble,xt=o.iterationDisplay!==Q,qt=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(le);(Ue||Mt||ut||wt||xt||qt)&&z&&(yl++,da(he,z.getMessages(),Fe));let ft=o.features?.streamAnimation?.type;if(ft!==re&&ft&&ft!=="none"){let ee=Ur(ft,o.features?.streamAnimation?.plugins);ee&&Ni(ee,e)}let ce=o.launcher??{},At=ce.headerIconHidden??!1,Gt=o.layout?.header?.showIcon,Ft=At||Gt===!1,rt=ce.headerIconName,$e=ce.headerIconSize??"48px";if(B){let ee=ue.querySelector(".persona-border-b-persona-divider"),ot=ee?.querySelector(".persona-flex-col");if(Ft)B.style.display="none",ee&&ot&&!ee.contains(ot)&&ee.insertBefore(ot,ee.firstChild);else{if(B.style.display="",B.style.height=$e,B.style.width=$e,ee&&ot&&(ee.contains(B)?B.nextSibling!==ot&&(B.remove(),ee.insertBefore(B,ot)):ee.insertBefore(B,ot)),rt){let Ke=parseFloat($e)||24,ct=ne(rt,Ke*.6,"currentColor",1);ct?B.replaceChildren(ct):B.textContent=ce.agentIconText??"\u{1F4AC}"}else if(ce.iconUrl){let Ke=B.querySelector("img");if(Ke)Ke.src=ce.iconUrl,Ke.style.height=$e,Ke.style.width=$e;else{let ct=document.createElement("img");ct.src=ce.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=$e,ct.style.width=$e,B.replaceChildren(ct)}}else{let Ke=B.querySelector("svg"),ct=B.querySelector("img");(Ke||ct)&&B.replaceChildren(),B.textContent=ce.agentIconText??"\u{1F4AC}"}let St=B.querySelector("img");St&&(St.style.height=$e,St.style.width=$e)}}let et=o.layout?.header?.showTitle,Pt=o.layout?.header?.showSubtitle;if(O&&(O.style.display=et===!1?"none":""),X&&(X.style.display=Pt===!1?"none":""),P){o.layout?.header?.showCloseButton===!1?P.style.display="none":P.style.display="";let ot=ce.closeButtonSize??"32px",St=ce.closeButtonPlacement??"inline";P.style.height=ot,P.style.width=ot;let{closeButtonWrapper:Ke}=Le,ct=St==="top-right",Vt=Ke?.classList.contains("persona-absolute");if(Ke&&ct!==Vt)if(Ke.remove(),ct)Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(Ke);else{let ze=ce.clearChat?.placement??"inline",Ot=ce.clearChat?.enabled??!0;Ke.className=Ot&&ze==="inline"?"":"persona-ml-auto";let nn=ue.querySelector(".persona-border-b-persona-divider");nn&&nn.appendChild(Ke)}if(P.style.color=ce.closeButtonColor||Qt.actionIconColor,ce.closeButtonBackgroundColor?(P.style.backgroundColor=ce.closeButtonBackgroundColor,P.classList.remove("hover:persona-bg-gray-100")):(P.style.backgroundColor="",P.classList.add("hover:persona-bg-gray-100")),ce.closeButtonBorderWidth||ce.closeButtonBorderColor){let ze=ce.closeButtonBorderWidth||"0px",Ot=ce.closeButtonBorderColor||"transparent";P.style.border=`${ze} solid ${Ot}`,P.classList.remove("persona-border-none")}else P.style.border="",P.classList.add("persona-border-none");ce.closeButtonBorderRadius?(P.style.borderRadius=ce.closeButtonBorderRadius,P.classList.remove("persona-rounded-full")):(P.style.borderRadius="",P.classList.add("persona-rounded-full")),ce.closeButtonPaddingX?(P.style.paddingLeft=ce.closeButtonPaddingX,P.style.paddingRight=ce.closeButtonPaddingX):(P.style.paddingLeft="",P.style.paddingRight=""),ce.closeButtonPaddingY?(P.style.paddingTop=ce.closeButtonPaddingY,P.style.paddingBottom=ce.closeButtonPaddingY):(P.style.paddingTop="",P.style.paddingBottom="");let dn=ce.closeButtonIconName??"x",Sn=ce.closeButtonIconText??"\xD7";P.innerHTML="";let Kt=ne(dn,"28px","currentColor",1);Kt?P.appendChild(Kt):P.textContent=Sn;let Et=ce.closeButtonTooltipText??"Close chat",cn=ce.closeButtonShowTooltip??!0;if(P.setAttribute("aria-label",Et),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),cn&&Et)){let ze=null,Ot=()=>{if(ze||!P)return;let Go=P.ownerDocument,Ca=Go.body;if(!Ca)return;ze=Hn(Go,"div","persona-clear-chat-tooltip"),ze.textContent=Et;let wa=Hn(Go,"div");wa.className="persona-clear-chat-tooltip-arrow",ze.appendChild(wa);let Ko=P.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(Mo),ze.style.left=`${Ko.left+Ko.width/2}px`,ze.style.top=`${Ko.top-8}px`,ze.style.transform="translate(-50%, -100%)",Ca.appendChild(ze)},nn=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};Ke.addEventListener("mouseenter",Ot),Ke.addEventListener("mouseleave",nn),P.addEventListener("focus",Ot),P.addEventListener("blur",nn),Ke._cleanupTooltip=()=>{nn(),Ke&&(Ke.removeEventListener("mouseenter",Ot),Ke.removeEventListener("mouseleave",nn)),P&&(P.removeEventListener("focus",Ot),P.removeEventListener("blur",nn))}}}let{clearChatButton:Be,clearChatButtonWrapper:tt}=Le;if(Be){let ee=ce.clearChat??{},ot=ee.enabled??!0,St=o.layout?.header?.showClearChat,Ke=St!==void 0?St:ot,ct=ee.placement??"inline";if(tt){tt.style.display=Ke?"":"none";let{closeButtonWrapper:Vt}=Le;!$()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Ke?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let dn=ct==="top-right",Sn=tt.classList.contains("persona-absolute");if(!$()&&dn!==Sn&&Ke){if(tt.remove(),dn)tt.className="persona-absolute persona-top-4 persona-z-50",tt.style.right="48px",ue.style.position="relative",ue.appendChild(tt);else{tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",tt.style.right="";let Et=ue.querySelector(".persona-border-b-persona-divider"),cn=Le.closeButtonWrapper;Et&&cn&&cn.parentElement===Et?Et.insertBefore(tt,cn):Et&&Et.appendChild(tt)}let Kt=Le.closeButtonWrapper;Kt&&!Kt.classList.contains("persona-absolute")&&(dn?Kt.classList.add("persona-ml-auto"):Kt.classList.remove("persona-ml-auto"))}}if(Ke){if(!$()){let ze=ee.size??"32px";Be.style.height=ze,Be.style.width=ze}let Vt=ee.iconName??"refresh-cw",dn=ee.iconColor??"";Be.style.color=dn||Qt.actionIconColor,Be.innerHTML="";let Sn=$()?"14px":"20px",Kt=ne(Vt,Sn,"currentColor",2);if(Kt&&Be.appendChild(Kt),ee.backgroundColor?(Be.style.backgroundColor=ee.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ze=ee.borderWidth||"0px",Ot=ee.borderColor||"transparent";Be.style.border=`${ze} solid ${Ot}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");ee.borderRadius?(Be.style.borderRadius=ee.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),ee.paddingX?(Be.style.paddingLeft=ee.paddingX,Be.style.paddingRight=ee.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),ee.paddingY?(Be.style.paddingTop=ee.paddingY,Be.style.paddingBottom=ee.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let Et=ee.tooltipText??"Clear chat",cn=ee.showTooltip??!0;if(Be.setAttribute("aria-label",Et),tt&&(tt._cleanupTooltip&&(tt._cleanupTooltip(),delete tt._cleanupTooltip),cn&&Et)){let ze=null,Ot=()=>{if(ze||!Be)return;let Go=Be.ownerDocument,Ca=Go.body;if(!Ca)return;ze=Hn(Go,"div","persona-clear-chat-tooltip"),ze.textContent=Et;let wa=Hn(Go,"div");wa.className="persona-clear-chat-tooltip-arrow",ze.appendChild(wa);let Ko=Be.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(Mo),ze.style.left=`${Ko.left+Ko.width/2}px`,ze.style.top=`${Ko.top-8}px`,ze.style.transform="translate(-50%, -100%)",Ca.appendChild(ze)},nn=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};tt.addEventListener("mouseenter",Ot),tt.addEventListener("mouseleave",nn),Be.addEventListener("focus",Ot),Be.addEventListener("blur",nn),tt._cleanupTooltip=()=>{nn(),tt&&(tt.removeEventListener("mouseenter",Ot),tt.removeEventListener("mouseleave",nn)),Be&&(Be.removeEventListener("focus",Ot),Be.removeEventListener("blur",nn))}}}}let ln=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ns],zo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[pr.message,pr.messageAndClick];M=os({parsers:ln,handlers:zo,getSessionMetadata:h,updateSessionMetadata:S,emit:l.emit,documentRef:typeof document<"u"?document:null}),Fe=Xg(o,M,Ee),z.updateConfig(o),da(he,z.getMessages(),Fe),hl(),Fu(),El(z.isStreaming());let mf=o.voiceRecognition?.enabled===!0,ks=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(mf&&(ks||Rt))if(!G||!Ve){let ee=yy(o.voiceRecognition,o.sendButton);ee&&(G=ee.micButton,Ve=ee.micButtonWrapper,nt.insertBefore(Ve,We),G.addEventListener("click",Ts),G.disabled=z.isStreaming())}else{let ee=o.voiceRecognition??{},ot=o.sendButton??{},St=ee.iconName??"mic",Ke=ot.size??"40px",ct=ee.iconSize??Ke,Vt=parseFloat(ct)||24;G.style.width=ct,G.style.height=ct,G.style.minWidth=ct,G.style.minHeight=ct;let dn=ee.iconColor??ot.textColor??"currentColor";G.innerHTML="";let Sn=ne(St,Vt,dn,2);Sn?G.appendChild(Sn):G.textContent="\u{1F3A4}";let Kt=ee.backgroundColor??ot.backgroundColor;Kt?G.style.backgroundColor=Kt:G.style.backgroundColor="",dn?G.style.color=dn:G.style.color="var(--persona-text, #111827)",ee.borderWidth?(G.style.borderWidth=ee.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ee.borderColor?G.style.borderColor=ee.borderColor:G.style.borderColor="",ee.paddingX?(G.style.paddingLeft=ee.paddingX,G.style.paddingRight=ee.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ee.paddingY?(G.style.paddingTop=ee.paddingY,G.style.paddingBottom=ee.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Et=Ve?.querySelector(".persona-send-button-tooltip"),cn=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&cn)if(Et)Et.textContent=cn,Et.style.display="";else{let Ot=document.createElement("div");Ot.className="persona-send-button-tooltip",Ot.textContent=cn,Ve?.insertBefore(Ot,G)}else Et&&(Et.style.display="none");Ve.style.display="",G.disabled=z.isStreaming()}else G&&Ve&&(Ve.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():In&&io());if(o.attachments?.enabled===!0)if(!Re||!Pe){let ee=o.attachments??{},St=(o.sendButton??{}).size??"40px";Ye||(Ye=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",Ae.insertBefore(Ye,q)),Te||(Te=document.createElement("input"),Te.type="file",Te.accept=(ee.allowedTypes??Xn).join(","),Te.multiple=(ee.maxFiles??4)>1,Te.style.display="none",Te.setAttribute("aria-label","Attach files"),Ae.insertBefore(Te,q)),Re=y("div","persona-send-button-wrapper"),Pe=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Pe.type="button",Pe.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ke=ee.buttonIconName??"paperclip",ct=St,Vt=parseFloat(ct)||40,dn=Math.round(Vt*.6);Pe.style.width=ct,Pe.style.height=ct,Pe.style.minWidth=ct,Pe.style.minHeight=ct,Pe.style.fontSize="18px",Pe.style.lineHeight="1";let Sn=ne(Ke,dn,"currentColor",1.5);Sn?Pe.appendChild(Sn):Pe.textContent="\u{1F4CE}",Pe.addEventListener("click",cn=>{cn.preventDefault(),Te?.click()}),Re.appendChild(Pe);let Kt=ee.buttonTooltipText??"Attach file",Et=y("div","persona-send-button-tooltip");Et.textContent=Kt,Re.appendChild(Et),Se?Se.append(Re):Ae.appendChild(Re),!Tt&&Te&&Ye&&(Tt=nr.fromConfig(ee),Tt.setPreviewsContainer(Ye),Te.addEventListener("change",async()=>{Tt&&Te?.files&&(await Tt.handleFileSelect(Te.files),Te.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Jg(ee.dropOverlay))}else{Re.style.display="";let ee=o.attachments??{};Te&&(Te.accept=(ee.allowedTypes??Xn).join(","),Te.multiple=(ee.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else Re&&(Re.style.display="none"),Tt&&Tt.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},xa=Nt.useIcon??!1,Ps=Nt.iconText??"\u2191",Ar=Nt.iconName,ba=Nt.tooltipText??"Send message",_l=Nt.showTooltip??!1,$o=Nt.size??"40px",Vn=Nt.backgroundColor,jo=Nt.textColor;if(xa){if(te.style.width=$o,te.style.height=$o,te.style.minWidth=$o,te.style.minHeight=$o,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",jo?te.style.color=jo:te.style.color="var(--persona-button-primary-fg, #ffffff)",Ar){let ee=parseFloat($o)||24,ot=jo?.trim()||"currentColor",St=ne(Ar,ee,ot,2);St?te.appendChild(St):te.textContent=Ps}else te.textContent=Ps;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Vn?(te.style.backgroundColor=Vn,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=o.copy?.sendButtonLabel??"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Vn?(te.style.backgroundColor=Vn,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),jo?te.style.color=jo:te.classList.add("persona-text-white");Nt.borderWidth?(te.style.borderWidth=Nt.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Nt.borderColor?te.style.borderColor=Nt.borderColor:te.style.borderColor="",Nt.paddingX?(te.style.paddingLeft=Nt.paddingX,te.style.paddingRight=Nt.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Nt.paddingY?(te.style.paddingTop=Nt.paddingY,te.style.paddingBottom=Nt.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let va=We?.querySelector(".persona-send-button-tooltip");if(_l&&ba)if(va)va.textContent=ba,va.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=ba,We?.insertBefore(ee,te)}else va&&(va.style.display="none");let Rs=o.layout?.contentMaxWidth??($()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Rs?(he.style.maxWidth=Rs,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Ae&&(Ae.style.maxWidth=Rs,Ae.style.marginLeft="auto",Ae.style.marginRight="auto"),bt&&(bt.style.maxWidth=Rs,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(he.style.maxWidth="",he.style.marginLeft="",he.style.marginRight="",he.style.width="",Ae&&(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let co=o.statusIndicator??{},Sy=co.visible??!0;if(I.style.display=Sy?"":"none",z){let ee=z.getStatus();Lt(I,(St=>St==="idle"?co.idleText??Wt.idle:St==="connecting"?co.connectingText??Wt.connecting:St==="connected"?co.connectedText??Wt.connected:St==="error"?co.errorText??Wt.error:Wt[St])(ee),co,ee)}I.classList.remove("persona-text-left","persona-text-center","persona-text-right");let My=co.align==="left"?"persona-text-left":co.align==="center"?"persona-text-center":"persona-text-right";I.classList.add(My)},open(){N()&&ht(!0,"api")},close(){N()&&ht(!1,"api")},toggle(){N()&&ht(!U,"api")},reconnect(){z.reconnectNow()},clearChat(){Nn=!1,z.clearMessages(),No.clear(),ao();try{localStorage.removeItem(Xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Xr)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),c?.clear&&Al(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Oe?.clear(),Xe?.reset(),qe?.update()},setMessage(i){return!q||z.isStreaming()?!1:(!U&&N()&&ht(!0,"system"),q.value=i,q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let m=i?.trim()||q.value.trim();return m?(!U&&N()&&ht(!0,"system"),q.value="",q.style.height="auto",z.sendMessage(m),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!U&&N()&&ht(!0,"system"),Je.manuallyDeactivated=!1,An(),z.toggleVoice().then(()=>{Je.active=z.isVoiceActive(),_n("user"),z.isVoiceActive()&&Cr()})),!0):In?!0:$u()?(!U&&N()&&ht(!0,"system"),Je.manuallyDeactivated=!1,An(),Ss("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,An(),_n("user"),qn()}),!0):!1:In?(Je.manuallyDeactivated=!0,An(),io("user"),!0):!1},injectMessage(i){return!U&&N()&&ht(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!U&&N()&&ht(!0,"system");let m=z.injectAssistantMessage(i);return fe&&(fe=!1,pe&&(clearTimeout(pe),pe=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),m},injectUserMessage(i){return!U&&N()&&ht(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!U&&N()&&ht(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!U&&N()&&ht(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!U&&N()&&ht(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!U&&N()&&ht(!0,"system"),z.injectTestEvent(i)},async connectStream(i,m){return z.connectStream(i,m)},__pushEventStreamEvent(i){Oe&&(Xe?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Z||!Oe||cl()},hideEventStream(){ke&&Zr()},isEventStreamVisible(){return ke},showArtifacts(){Yt(o)&&(Nn=!1,fr=!0,On(),Ze?.setMobileOpen(!0))},hideArtifacts(){Yt(o)&&(Nn=!0,On())},upsertArtifact(i){return Yt(o)?(Jo(o.features?.artifacts,i.artifactType)==="panel"&&(Nn=!1,fr=!0),z.upsertArtifact(i)):null},selectArtifact(i){Yt(o)&&z.selectArtifact(i)},clearArtifacts(){Yt(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return A&&!U&&!$()||!q?!1:(q.focus(),!0)},async resolveApproval(i,m,x){let L=z.getMessages().find(H=>H.variant==="approval"&&H.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,x)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(i){S(i)},on(i,m){return l.on(i,m)},off(i,m){l.off(i,m)},isOpen(){return N()&&U},isVoiceActive(){return Je.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:N()&&U,launcherEnabled:A,voiceActive:Je.active,streaming:z.isStreaming()}},showCSATFeedback(i){!U&&N()&&ht(!0,"system");let m=he.querySelector(".persona-feedback-container");m&&m.remove();let x=tl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});he.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!U&&N()&&ht(!0,"system");let m=he.querySelector(".persona-feedback-container");m&&m.remove();let x=nl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});he.appendChild(x),x.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return z.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return z.submitNPSFeedback(i,m)},destroy(){Rl(),Uo!=null&&(clearInterval(Uo),Uo=null),je.forEach(i=>i()),Me.remove(),lt?.remove(),_t?.destroy(),$t?.remove(),Fo&&P.removeEventListener("click",Fo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Ht,getMessages:Ht.getMessages,getStatus:Ht.getStatus,getMetadata:Ht.getPersistentMetadata,updateMetadata:Ht.updatePersistentMetadata,clearHistory:()=>Ht.clearChat(),setVoiceActive:x=>x?Ht.startVoiceRecognition():Ht.stopVoiceRecognition()};window.AgentWidgetBrowser=m,je.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 K=V.detail;(!K?.instanceId||K.instanceId===i)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",m),je.push(()=>{window.removeEventListener("persona:focusInput",m)}),Z){let V=oe=>{let le=oe.detail;(!le?.instanceId||le.instanceId===i)&&Ht.showEventStream()},K=oe=>{let le=oe.detail;(!le?.instanceId||le.instanceId===i)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",K),je.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",K)})}let x=V=>{let K=V.detail;(!K?.instanceId||K.instanceId===i)&&Ht.showArtifacts()},v=V=>{let K=V.detail;(!K?.instanceId||K.instanceId===i)&&Ht.hideArtifacts()},L=V=>{let K=V.detail;K?.instanceId&&K.instanceId!==i||K?.artifact&&Ht.upsertArtifact(K.artifact)},H=V=>{let K=V.detail;K?.instanceId&&K.instanceId!==i||typeof K?.id=="string"&&Ht.selectArtifact(K.id)},Q=V=>{let K=V.detail;(!K?.instanceId||K.instanceId===i)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",x),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",Q),je.push(()=>{window.removeEventListener("persona:showArtifacts",x),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",Q)})}let yn=hC(o.persistState);if(yn&&N()){let i=yC(yn.storage),m=`${yn.keyPrefix}widget-open`,x=`${yn.keyPrefix}widget-voice`,v=`${yn.keyPrefix}widget-voice-mode`;if(i){let L=yn.persist?.openState&&i.getItem(m)==="true",H=yn.persist?.voiceState&&i.getItem(x)==="true",Q=yn.persist?.voiceState&&i.getItem(v)==="true";if(L&&setTimeout(()=>{Ht.open(),setTimeout(()=>{if(H||Q)Ht.startVoiceRecognition();else if(yn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),yn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(m,"true")}),l.on("widget:closed",()=>{i.setItem(m,"false")})),yn.persist?.voiceState&&(l.on("voice:state",V=>{i.setItem(x,V.active?"true":"false")}),l.on("user:message",V=>{i.setItem(v,V.viaVoice?"true":"false")})),yn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(x),i.removeItem(v)},K=()=>V();window.addEventListener("persona:clear-chat",K),je.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(g&&N()&&setTimeout(()=>{Ht.open()},0),xr(),!qh){let i=Mr(()=>{z&&(yl++,No.clear(),da(he,z.getMessages(),Fe))});je.push(i)}return Ht};var Qg=(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},vC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},CC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},wC=(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.")},Yg=(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"},Gp=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=""},Zg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Gp(e)},zp=e=>{e.style.transition=""},$p=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=""},jp=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},al=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},AC=(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))},SC=(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)},MC=e=>{let t=wo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Jt(t,r)??r;return{inset:o(n?.inset,bi),canvasBackground:o(n?.canvasBackground,vi)}},eh=(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},TC=(e,t,n,o,r,a,s,l)=>{let p=on(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";AC(e,t,n,o,c),SC(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.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,S=a?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=S:!1;if(h&&E&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$p(t),zp(o),Zg(o),jp(n),al(r,o),eh(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??zt),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"),Zg(o),vC(o,p.maxHeight),eh(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",$p(t),zp(o),jp(n),al(r,o);let M=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",w=s?"translateX(0)":A;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=w,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",zp(o),Gp(o),al(r,o);let M=Qg(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),w=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=`${A+M}px`,t.style.transition=w,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=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}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="",$p(t),Gp(o),jp(n),al(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=s?p.width:"0px",w=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 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",CC(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=w,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let R=d?`calc(${Qg(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=R,r.style.minWidth=R,r.style.maxWidth=R,r.style.boxSizing="border-box"}}},EC=(e,t)=>{let n=e.ownerDocument.createElement("div");return Yg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Yg(n,o)},destroy(){n.remove()}}},kC=(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,S=()=>{h=t?.launcher?.detachedPanel===!0?MC(t):null};S();let E=()=>{TC(s,l,p,c,d,t,u,h)},k=null,M=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Dr(()=>{S(),E()}))},A=()=>{f(),on(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{E()}),g.observe(s)))},w=!1,T=()=>{E(),A(),u&&!w&&s.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,wC(s,on(t)))},R=s.ownerDocument.defaultView,b=()=>{T()};return R?.addEventListener("resize",b),on(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(W){let F=W.launcherEnabled?W.open:!0;u!==F&&(u=F,T())},updateConfig(W){t=W,(t?.launcher?.enabled??!0)===!1&&(u=!0),S(),T(),M()},destroy(){R?.removeEventListener("resize",b),k?.(),k=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},as=(e,t)=>It(t)?kC(e,t):EC(e,t);var LC=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},th=(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)},nh=e=>{let t=LC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=as(t,r),s,l=[],p=(E,k)=>{let A=!(k?.launcher?.enabled??!0)||It(k),w=o.createElement("div");if(w.setAttribute("data-persona-root","true"),A&&(w.style.height="100%",w.style.display="flex",w.style.flexDirection="column",w.style.flex="1",w.style.minHeight="0"),n){let T=E.attachShadow({mode:"open"});T.appendChild(w),th(T,o)}else E.appendChild(w),th(E,o);return t.id&&w.setAttribute("data-persona-instance",t.id),w},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=rl(E,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(E=>E()),l=[],s.destroy()};u(),e.onChatReady?.();let f=E=>{g(),a.destroy(),a=as(t,E),r=E,u()},h={update(E){let k={...r,...E,launcher:{...r?.launcher??{},...E?.launcher??{},dock:{...r?.launcher?.dock??{},...E?.launcher?.dock??{}}}},M=It(r),A=It(k),w=Po(r),T=Po(k);if(M!==A||w!==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]}},S=new Proxy(h,{get(E,k,M){if(k==="host")return a.host;if(k in E)return Reflect.get(E,k,M);let A=s[k];return typeof A=="function"?A.bind(s):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};function PC(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 RC(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:PC(o,n)?2:3}function oh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function sl(e,t){let n=t.trim();if(!n)return[...e].sort(oh);let o=[];for(let r of e){let a=RC(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:oh(r.item,a.item)),o.map(r=>r.item)}function IC(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 rh(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>sl(e.items,t),resolve:e.resolve}}function ah(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=>sl(t,IC(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 ch=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),BC=new Set(["button","a","input","select","textarea","details","summary"]),HC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Kp=/\b(product|card|item|listing|result)\b/i,Jp=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,WC=3e3,DC=100;function ph(e){let t=typeof e.className=="string"?e.className:"";if(Kp.test(t)||e.id&&Kp.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Kp.test(o.value))return!0}return!1}function uh(e){return Jp.test((e.textContent??"").trim())}function fh(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 FC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function sh(e){let t=e.match(Jp);return t?t[0]:null}function ih(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 NC(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 OC="commerce-card",_C="result-card";function lh(e){return!ph(e)||!uh(e)||!fh(e)&&!FC(e)?0:5200}function dh(e){return!ph(e)||uh(e)||!fh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Qp=[{id:OC,scoreElement(e){return lh(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||Jp.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(lh(e)===0)return null;let{title:n,href:o}=ih(e),r=sh((e.textContent??"").trim())??sh(t.text)??"",a=NC(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:_C,scoreElement(e){return dh(e)},formatSummary(e,t){if(dh(e)===0)return null;let{title:n,href:o}=ih(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function UC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function qC(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??Qp;return l==="simple"&&e.rules&&e.rules.length>0?(UC(),c=[]):l==="simple"&&(c=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:c}}function Xp(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var VC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function zC(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"||BC.has(t)||n&&HC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function mh(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 $C(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 Yp(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Xp(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of VC){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${Xp(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=>Xp(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 jC(e){return e==="static"?DC:WC}function gh(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Yp(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:zC(e),attributes:$C(e)}}function GC(e,t,n,o){let r=jC(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 KC(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 XC(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(ch.has(d)){l=s.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!mh(c)){l=s.nextNode();continue}let u=gh(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:S}=GC(c,u,e.rules,n);r.push({el:c,domIndex:a,enriched:u,score:h,formattingRule:S}),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;KC(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 JC(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(ch.has(c)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!mh(p)){a=r.nextNode();continue}let d=gh(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 hh(e={}){let t=qC(e),n=t.root??document.body;return n?t.mode==="simple"?JC(t,n):XC(t,n):[]}var il=100;function yh(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
|
+
${a.map(s=>`- ${s.split(`
|
|
116
147
|
`).join(`
|
|
117
148
|
`)}`).join(`
|
|
118
|
-
`)}`)}let
|
|
119
|
-
${
|
|
120
|
-
`)}`)}if(
|
|
121
|
-
${
|
|
122
|
-
`)}`)}if(
|
|
123
|
-
${
|
|
124
|
-
`)}`)}if(
|
|
125
|
-
${
|
|
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,il)}" (clickable)`);o.push(`Interactive elements:
|
|
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,il)}" (navigable)`);o.push(`Navigation links:
|
|
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,il)}" (input)`);o.push(`Form inputs:
|
|
154
|
+
${a.join(`
|
|
155
|
+
`)}`)}if(r.static.length>0){let a=r.static.map(s=>`- ${s.selector}: "${s.text.substring(0,il)}"`);o.push(`Content:
|
|
156
|
+
${a.join(`
|
|
126
157
|
`)}`)}return o.join(`
|
|
127
158
|
|
|
128
|
-
`)}function
|
|
159
|
+
`)}function xh(){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 bh(){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 vh(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:Fn(e.colors.primary,.95),100:Fn(e.colors.primary,.9),200:Fn(e.colors.primary,.8),300:Fn(e.colors.primary,.7),400:Fn(e.colors.primary,.6),500:e.colors.primary,600:Fn(e.colors.primary,.8),700:Fn(e.colors.primary,.7),800:Fn(e.colors.primary,.6),900:Fn(e.colors.primary,.5),950:Fn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Ch(){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 wh(){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 Fn(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 Ah(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var QC={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"}}},Sh={components:{panel:{borderRadius:"0",shadow:"none"}}},Zp={id:"shop",label:"Shopping Assistant",config:{theme:QC,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?"]}},eu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Sh}},tu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Sh}},nu={shop:Zp,minimal:eu,fullscreen:tu};function Mh(e){return nu[e]}var YC=`
|
|
129
160
|
@keyframes persona-stream-wipe {
|
|
130
161
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
131
162
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|
|
@@ -161,7 +192,7 @@ ${s.join(`
|
|
|
161
192
|
mask-image: none !important;
|
|
162
193
|
}
|
|
163
194
|
}
|
|
164
|
-
`.trim(),
|
|
195
|
+
`.trim(),ZC={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:YC};ar(ZC);var ew=`
|
|
165
196
|
[data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
|
|
166
197
|
animation: persona-stream-glyph-cycle-fade
|
|
167
198
|
calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
|
|
@@ -179,7 +210,7 @@ ${s.join(`
|
|
|
179
210
|
opacity: 1 !important;
|
|
180
211
|
}
|
|
181
212
|
}
|
|
182
|
-
`.trim(),
|
|
213
|
+
`.trim(),ss="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",tw=10,nw=120,ou=120,ow=.4,rw=50,aw=e=>{if(!e)return ou;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):ou},Bh=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=aw(t);return nw*n/ou},ru=e=>{let t=ss[Math.floor(Math.random()*ss.length)];return e&&t===e&&(t=ss[(ss.indexOf(t)+1)%ss.length]),t},sw=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()<ow&&(r.textContent=ru())}},Th=new WeakMap,Eh=25,kh=.5,iw=6,Lh=.25,Ph=new WeakMap,Rh=new WeakMap,lw=(e,t)=>{if(!e)return Eh*kh;let n=Ph.get(e);Ph.set(e,t);let o=Rh.get(e)??Eh;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Lh)+r*Lh,Rh.set(e,o))}return Math.max(iw,o*kh)},Jr=new Map,dw=e=>e.closest("[data-message-id]")?.dataset.messageId??null,cw=e=>{e&&Jr.set(e,(Jr.get(e)??0)+1)},pw=e=>{if(!e)return;let t=Jr.get(e)??0;t<=1?Jr.delete(e):Jr.set(e,t-1)},Hh=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=ru();let n=dw(e);n&&(e.dataset.glyphCycleMessageId=n),cw(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=lw(o,r),s=Bh(e),l=tw*s,p=r+l;if(o){let c=Th.get(o);c!==void 0&&(p=Math.max(p,c)),Th.set(o,p+a)}uw(e,t,p)},uw=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Bh(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,pw(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=ru(r);e.textContent=s,r=s,sw(e),setTimeout(a,o)};setTimeout(a,o)},Ih=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))Hh(n)},fw=e=>e.nodeType===1,mw={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:ew,bufferContent(e){if(e.length<rw)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(Jr.get(e.id)??0)>0},onAttach(e){Ih(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))fw(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?Hh(r):Ih(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};ar(mw);var Zt=typeof document<"u"?document.currentScript?.src??null:null;Pf(()=>{let e=Zt?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===Zt?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${Zt??"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)});xf(()=>{let e=Zt?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===Zt?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${Zt??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});Sa().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});mm(()=>{let e=Zt?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===Zt?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${Zt??"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)});Sm(()=>{let e=Zt?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===Zt?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${Zt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});Mm(()=>{let e=Zt?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===Zt?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${Zt??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return Iy(gw);})();
|
|
183
214
|
/*! Bundled license information:
|
|
184
215
|
|
|
185
216
|
lucide/dist/esm/icons/activity.mjs:
|
|
@@ -207,6 +238,7 @@ lucide/dist/esm/icons/circle-x.mjs:
|
|
|
207
238
|
lucide/dist/esm/icons/clipboard-copy.mjs:
|
|
208
239
|
lucide/dist/esm/icons/clipboard.mjs:
|
|
209
240
|
lucide/dist/esm/icons/clock.mjs:
|
|
241
|
+
lucide/dist/esm/icons/code-xml.mjs:
|
|
210
242
|
lucide/dist/esm/icons/copy.mjs:
|
|
211
243
|
lucide/dist/esm/icons/credit-card.mjs:
|
|
212
244
|
lucide/dist/esm/icons/dollar-sign.mjs:
|